Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
useReducer is a React hook that allows managing component state using a reducer — a function similar to reducer from Redux.
It's especially useful when:
const [state, dispatch] = useReducer(reducer, initialState);
reducer — function that accepts state and action, and returns new state.initialState — initial state.state — current state.dispatch(action) — way to trigger state update.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:
return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
<button onClick={() => dispatch({ type: "increment" })}>+</button>
</div>
);
}
Reducer is a pure function that has no side effects and always returns new state based on current state and action.
(state, action) => newState
useReducer advantage:
The useReducer hook helps organize business logic separately from components, making them cleaner and easier to test.
useReducer is an alternative to useState, especially useful for complex state logic.