FrontendDeveloper.in

React question detail

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.

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.
import React, { useReducer } from 'react';

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

return (
<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>
);
}

export default Counter;

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

Back to all React questions
Get LinkedIn Premium at Rs 399