The useReducer
hook in React is an alternative to useState
, allowing for managing more complex state logic in functional components. useReducer
is often used when the component state depends on multiple actions or is more complex.
Syntax of useReducer
:
const [state, dispatch] = useReducer(reducer, initialState);
Example of using useReducer
:
- Defining the reducer:
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(); } }
- Using
useReducer
in a component:
import React, { useReducer } from 'react'; const initialState = { count: 0 }; 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> ); }
The useReducer
hook is useful when you need more advanced state management, similar to Redux
, but within React functional components.