iTranslated by AI
The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
😆
Understanding the 10 React Hooks (Additional: useReducer)
Understanding the 10 React Hooks (Basic: useReducer)
What is useReducer?
-
useReduceris an alternative touseState. - It is used when you have complex state logic that involves multiple values or when the next state depends on the previous state.
- It accepts a reducer with the signature
(state, action) => newState()and returns the current state paired with adispatchmethod. - It helps with performance optimization because you can pass
dispatchdown to child components instead of callbacks.
const [state, dispatch] = useReducer(reducer, initialArg, init);
Comparison between useState and useReducer (from official docs)
Using useState
function Counter({initialCount}) {
const [count, setCount] = useState(initialCount);
return (
<>
Count: {count}
<button onClick={() => setCount(initialCount)}>Reset</button>
<button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
<button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
</>
);
}
Using useReducer
function init(initialCount) {
return {count: initialCount};
}
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
case 'reset':
return init(action.payload);
default:
throw new Error();
}
}
function Counter({initialCount}) {
const [state, dispatch] = useReducer(reducer, initialCount, init);
return (
<>
Count: {state.count}
<button
onClick={() => dispatch({type: 'reset', payload: initialCount})}>
Reset
</button>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</>
);
}
How to Initialize useReducer
Specifying the Initial State
const [state, dispatch] = useReducer(
reducer,
{count: initialCount}
);
Lazy Initialization
- Pass an
initfunction as the third argument (as seen in the "UsinguseReducer" section above).
Bailing Out of a Dispatch
- If you return the same value from a reducer as the current state, React will bail out without rendering the children or firing effects.
Discussion