The useReducer
hook in React is a more advanced alternative to the useState
hook for managing complex state logic in your components. It is particularly useful when the state logic involves multiple sub-values or when the next state depends on the previous one. The useReducer
hook is inspired by the reducer functions used in Redux.
Here's how you can use the useReducer
hook:
Importing the Hook:
Make sure to import the
useReducer
hook at the top of your file:import React, { useReducer } from 'react';
Defining the Reducer Function:
You need to define a reducer function that specifies how the state should be updated based on dispatched actions. The reducer function takes two arguments: the current state and an action object. It returns the new state.
const reducer = (state, action) => { switch (action.type) { case 'INCREMENT': return { count: state.count + 1 }; case 'DECREMENT': return { count: state.count - 1 }; default: return state; } };
Initializing State:
You can initialize the state using the
useReducer
hook. Pass the reducer function and the initial state as arguments touseReducer
.const initialState = { count: 0 }; const [state, dispatch] = useReducer(reducer, initialState);
Dispatching Actions:
To update the state, you dispatch actions. An action is an object that typically includes a
type
property to indicate the type of action and optionally apayload
property for additional data.<button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button> <button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button>
Accessing State:
You can access the state values from the
state
object returned byuseReducer
.Here's a complete example demonstrating the use of
useReducer
:import React, { useReducer } from 'react'; const initialState = { count: 0 }; const reducer = (state, action) => { switch (action.type) { case 'INCREMENT': return { count: state.count + 1 }; case 'DECREMENT': return { count: state.count - 1 }; default: return state; } }; const Counter = () => { const [state, dispatch] = useReducer(reducer, initialState); return ( <div> <p>Count: {state.count}</p> <button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button> <button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button> </div> ); }; export default Counter;
In this example, we have a simple counter component that increments or decrements a count value using
useReducer
.