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:
- 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;
}
}
- Using
useReducer: InvokeuseReducerwith 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.