InterviewHubPRO
Section Overview
Q277

Question 277 of 445

Part 9: React Hooks Deep Dive (262 - 316)

62%
React & Modern Frontend (445 Qs)•Part 9: React Hooks Deep Dive (262 - 316)

How does useReducer works? Explain with an example

The useReducer hooks works similarly to Redux, where:

  • You define a reducer function to handle state transitions.
  • You dispatch actions to update the state.

Counter Example with Increment, Decrement, and Reset:

  1. Reducer function:

Define a counter reducer function that takes the current state and an action object with a type, and returns a new state based on that type.

js
  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:
         return state;
     }
   }
  1. Using useReducer: Invoke useReducer with above reducer function along with initial state. Thereafter, you can attach dispatch actions for respective button handlers.
js
import React, { useReducer } from 'react';

 function Counter() {
   const initialState = { count: 0 };
   const [state, dispatch] = useReducer(counterReducer, initialState);

   return (
     <div style={{ textAlign: 'center' }}>
       <h2>Count: {state.count}</h2>
       <button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
       <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
       <button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
     </div>
   );
 }

export default Counter;

Once the new state has been returned, React re-renders the component with the updated state.count.