In React, useReducer is a React hook used for managing more complex state logic in functional components.
It is particularly useful when state transitions depend on the previous state or when the next state is calculated based on the current state and an action.
import React, { useReducer } from 'react'; const reducer = (state, action) => { switch (action.type) { case 'ACTION_TYPE': return { count: state.count - 1 }; default: // if no case match return default state return state; } }; const YourCounterComponent = () => { const [state, dispatch] = useReducer(reducer, INITIAL_STATE); return ( <div> <button onClick={() => dispatch({ type: 'ACTION_TYPE' })}> Dispatch Action to Reducer </button> </div> ); }; export default YourCounterComponent;
`useReducer` hook is often chosen over `useState` in situations where the state logic is more complex or when multiple actions need to be handled in a more structured manner.
import React, { useReducer } from 'react'; // Reducer function defines how state changes in response to actions const reducer = (state, action) => { switch (action.type) { case 'DECREMENT': return { count: state.count - 1 }; case 'INCREMENT': return { count: state.count + 1 }; case 'SET_ZERO': return { count: 0 }; default: // if none of the above case match default state return return state; } }; const YourCounterComponent = () => { // useReducer returns the current state and a dispatch function const [state, dispatch] = useReducer(reducer, { count: 0 }); return ( <div> <p>Count: {state.count}</p> <button onClick={() => dispatch({ type: 'INCREMENT' })}> Increment </button> <button onClick={() => dispatch({ type: 'DECREMENT' })}> Decrement </button> <button onClick={() => dispatch({ type: 'SET_ZERO' })}> Set Count 0 </button> </div> ); }; export default YourCounterComponent;
The `reducer` function takes the current state and an action as parameters and returns the new state.
The `useReducer` hook is initialized with the `reducer` function and an `initial state`.
The `useReducer` hook returns an array with two elements: the `current state (state)` and a `dispatch` function. The dispatch function is used to trigger state transitions by dispatching actions to a reducer.
The component uses the state to display the current count and the dispatch function to `increment`, `decrement` and `set count 0` to modify count value based on the dispatched actions.