Contents of React Interview Questions

Comprehensive collection of React interview questions and answers covering hooks, components, state management, and best practices.

Difference between useState and useReducer hooks

Both useState and useReducer are Hooks for managing state, but they are suited for different situations:

AspectuseStateuseReducer
UsageSimple state (strings, numbers, booleans, objects)Complex state logic involving multiple sub-values or transitions
ParametersInitial state valueReducer function + initial state
UpdatesDirectly using the state setterDispatching actions to modify state
Best forSmall, straightforward updatesComplex updates, dependent states, or when the next state depends heavily on the previous one

Example use case:

  • useState → toggling a modal.
  • useReducer → managing a shopping cart.

Example for useState

Suppose you want to manage a simple counter:

import { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </> ); }

✅ Here:

  • useState(0) initializes count to 0.
  • setCount updates the count.
  • Every time setCount is called, the component re-renders.

Example for useReducer

Suppose the counter has more complex logic (increment, decrement, and reset):

import { useReducer } from 'react'; // Reducer function function counterReducer(state, action) { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; case 'reset': return { count: 0 }; default: throw new Error(); } } function CounterWithReducer() { const [state, dispatch] = useReducer(counterReducer, { count: 0 }); return ( <> <p>Count: {state.count}</p> <button onClick={() => dispatch({ type: 'increment' })}>Increment</button> <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button> <button onClick={() => dispatch({ type: 'reset' })}>Reset</button> </> ); }

✅ Here:

  • useReducer(counterReducer, { count: 0 }) initializes state.
  • dispatch is used to send actions to the reducer.
  • The reducer updates the state based on action type.

Quick visual:

When to preferExample
useStateSimple toggles, input field values
useReducerForms with multiple fields, complex state transitions, multiple related values