BP218: Use the useReducer hook to manage complex state
Use the useReducer hook to manage complex state in React functional components. The useReducer hook is a powerful tool for managing state in React functional components. It allows you to handle complex state logic in a more organized and predictable way than using the useState hook alone.
The useReducer hook takes two arguments: a reducer function and an initial state value. The reducer function takes two arguments: the current state and an action object, and returns the new state. Actions are objects that describe what changes should be made to the state. By convention, actions have a type property that describes the type of change to be made, and a payload property that contains any data needed to make the change.
Here's an example of how to use the useReducer hook to manage a counter:
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 (
<div>
Count: {state.count}
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</div>
);
}
export default Counter;
In this example, we define an initial state object with a count property set to 0. We also define a reducer function that takes the current state and an action object, and returns the new state based on the action type. In the Counter component, we use the useReducer hook to initialize the state with the initial state object and the reducer function. We then render the current count value and two buttons that dispatch actions to increment or decrement the count.