What is useReducer in React: Simple Explanation and Example
useReducer is a React hook that helps manage complex state logic by using a reducer function to update state based on actions. It works like a simple state machine where you send actions and get new state, making it easier to handle multiple related state changes.How It Works
Imagine you have a smart assistant who listens to your commands and changes things accordingly. In React, useReducer works like that assistant. You give it a current state and a command (called an action), and it decides what the new state should be.
This happens through a reducer function, which is like a rulebook. It looks at the current state and the action, then returns the updated state. This way, you keep your state changes organized and predictable, especially when the state has many parts or complex updates.
Think of it like managing a to-do list: instead of changing the list directly, you send commands like "add item" or "remove item," and the reducer updates the list for you.
Example
This example shows a counter that can be increased, decreased, or reset using useReducer. It demonstrates how actions control state changes clearly.
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 }; case 'reset': return initialState; default: throw new Error('Unknown action'); } } export default function Counter() { const [state, dispatch] = useReducer(reducer, initialState); return ( <div> <p>Count: {state.count}</p> <button onClick={() => dispatch({ type: 'increment' })}>+</button> <button onClick={() => dispatch({ type: 'decrement' })}>-</button> <button onClick={() => dispatch({ type: 'reset' })}>Reset</button> </div> ); }
When to Use
Use useReducer when your component has complex state logic involving multiple sub-values or when the next state depends on the previous one. It is especially helpful when you have many related state updates triggered by different actions.
For example, managing form inputs with validation, toggling UI elements based on various events, or handling state in games or interactive apps can benefit from useReducer. It keeps your code clean and easier to maintain compared to many useState calls.
Key Points
- useReducer manages state with a reducer function and actions.
- It is great for complex or related state updates.
- Actions describe what change to make, keeping logic clear.
- Helps keep state updates predictable and organized.
- Works well for forms, counters, toggles, and more complex UI states.
Key Takeaways
useReducer is a React hook for managing complex state with a reducer function.useState calls.