When your React components get more complex, managing state with just useState can get messy. This is where useReducer
shines! Itβs great for handling more complex state logic.
πΉ Example: Managing a counter with useReducer
import { 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:
throw new Error();
}
}
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>
</div>
);
}
Why use useReducer
?
π Simplifies complex state logic
π§ Makes state management predictable
π Scales better with larger components
π‘ Have you tried useReducer
in your projects? Share your experience or any tips you have! π
Top comments (0)