In React, the useReducer
hook is used to manage complex state and actions. It provides a way to manage state by accepting a reducer function and an initial state.
The useReducer
hook returns an array with two elements: the current state and a dispatch function. The dispatch function is used to update the state by providing an action object that describes the state change.
Here's an example of how to use the useReducer
hook:
JAVASCRIPT
1import React, { useReducer } from 'react';
2
3const initialState = {
4 count: 0,
5};
6
7function reducer(state, action) {
8 switch(action.type) {
9 case 'increment':
10 return { count: state.count + 1 };
11 case 'decrement':
12 return { count: state.count - 1 };
13 default:
14 return state;
15 }
16}
17
18function Counter() {
19 const [state, dispatch] = useReducer(reducer, initialState);
20
21 return (
22 <div>
23 <p>Count: {state.count}</p>
24 <button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
25 <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
26 </div>
27 );
28}
29```+
30
31In this example, we first define an `initialState` object that contains the initial value for the `count` property. We then define a `reducer` function that takes the current state and an action object as parameters. The reducer function uses a `switch` statement to determine how the state should be updated based on the action type.
32
33In the `Counter` component, we use the `useReducer` hook to initialize the state with the `reducer` function and `initialState`. We destructure the `state` and `dispatch` from the `useReducer` return value.
34
35Finally, we render the `state.count` value and provide `onClick` handlers for the `increment` and `decrement` buttons. When a button is clicked, we call the `dispatch` function with the appropriate action type to update the state.
36
37The `useReducer` hook is a powerful tool for managing complex state and actions in React components. It provides a declarative way to update state and ensures that state transitions are handled consistently.
38
39Feel free to experiment further with the `useReducer` hook to manage more complex state and actions in your React applications.