Junior — Middle
Explain the working principle of the useReducer hook in React and when it is recommended to use it.
sobes.tech AI
Answer from AI
The useReducer hook in React is used for managing complex component state, especially when the logic for updating the state depends on the previous state or when there are multiple related values.
How it works:
useReducertakes a reducer — a function that receives the current state and an action, and returns a new state.- It returns an array with the current state and a
dispatchfunction, which can be used to send actions to update the state.
It is recommended to use useReducer when:
- The state is complex and contains multiple subfields.
- The logic for updating the state is complex and depends on the action type.
- You need to manage state changes centrally.
Example:
import React, { useReducer } from 'react';
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</>
);
}