Managing State with useReducer
The `useReducer` hook provides centralized state management, especially useful for complex state logic with multiple transitions.
Key concepts
useReducer
A hook that provides centralized state management, especially useful for complex state logic with multiple transitions.
Step by step
When to Use:
- Complex state transitions with multiple actions.
- Managing state in a scalable and maintainable way.
Examples
useReducer Example:
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 };
default:
return state;
}
}
function 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>
);
}Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus