
What does the useReducer hook do
Requirements
- React.js (16.8 or newer)
What is it?
The useReducer hook is a way to manage state in React. It's similar to the useState hook, but it allows you to manage complex state objects and update them in a more predictable way.
Here's an example of how you might use the useReducer hook to manage a simple counter:
import { useReducer } from 'react'; 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(); } }
How to use it?
function Counter() { const [state, dispatch] = useReducer(reducer, { count: 0 }); return ( <> <button onClick={() => dispatch({ type: 'decrement' })}>-</button> <span>{state.count}</span> <button onClick={() => dispatch({ type: 'increment' })}>+</button> </> ); }
In this example, we have a reducer function that takes in a state object and an action object, and returns a new state based on the action type. The useReducer hook returns an array containing the current state and a dispatch function, which we can use to update the state by calling dispatch with an action object.
We can then use the state and dispatch function in our component to render the current count and define buttons that increment or decrement the count when clicked.
TLDR
The useReducer hook is a way to manage state in a React component. It allows you to update complex state objects in a more predictable way, and is similar to the useState hook but for more advanced state management scenarios.
Related Posts
- What is React's useCallback?2021-09-02
- What does the useReducer hook do2023-01-05
- How to use Debounce in Reactjs?2023-01-04
- What is React's useMemo2021-09-02
- What is React's Context API?2021-08-28
- React - What is Prop Drilling?2021-08-28
- React - Controlled Vs Uncontrolled2021-08-27