The useReducer hook is an alternative to the useState hook that is preferred when you have complex state logic. It is useful when the state transitions depend on previous state values or when you need to handle actions that can update the state differently.
Syntax:
const [state, dispatch] = useReducer(reducer, initialState);
reducer: A function that defines how the state should be updated based on the action. It takes two parameters: the current state and the action.
initialState: The initial value of the state.
State The current state returned from the useReducer hook.
dispatch: A function used to send an action to the reducer to update the state
state.count
import React, { useReducer } from 'react';
const counterReducer = (state, action) => {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
case 'reset':
return { count:0 };
default:
return state;
}
};
function Counter() {
const [state, dispatch] = useReducer(counterReducer, { count: 0 });
return (
Count: {state.count}
dispatch({ type: 'INCREMENT' })}>Increment
dispatch({ type: 'DECREMENT' })}>Decrement
button onClick={() => dispatch({ type: 'reset' })}>Decrement
);
}
export default Counter;
Top comments (0)