- useReducer is a React Hook that lets you manage state in a functional component. It’s similar to useState but with additional features for managing complex state transitions and updates.
- useReducer takes two arguments: the first is a reducer function, and the second is the initial state. The reducer function takes the current state and an action as arguments and returns a new state. The action is an object that describes an action that should be performed on the state.
Code example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import React, { useReducer } from 'react'; import ReactDOM from 'react-dom/client'; function reducer(state, action) { switch (action.type) { case 'increase': return { count: state.count + 1 }; case 'decrease': return { count: state.count - 1 }; default: throw new Error(); } } //App function component function App() { const [state, dispatch] = useReducer(reducer,{ count: 0 }); return ( <div> <p>Count: {state.count}</p> <button onClick={() => dispatch({ type: 'decrease' })}>-</button> <button onClick={() => dispatch({ type: 'increase' })}>+</button> </div> ); } const root = ReactDOM.createRoot(document.getElementById("root")); //creating a root React component in your application root.render(<App />) // rendering React components into a DOM node. |
In this above example, the useReducer
Hook returns an array with two values: state
and dispatch
, where state
is the current state of the component & the dispatch
function is used to update the state by sending an action to the reducer function. When you call dispatch
with an action, the reducer function is called with the current state and the action, and it returns the new state.
Output:
