Import the Hook:
Import the useReducer hook from React. Using useReducer in React is a way to manage state in a more complex or structured manner, especially when the state logic involves multiple sub-values or requires actions based on the previous state. Here's a guide on how to use and implement useReducer, and when it's appropriate to do so .
When to Use useReducer:
- Complex State Logic: Use useReducer when you have complex state logic that involves multiple sub-values or requires actions based on the previous state.
- State Transition Based on Actions: Use useReducer when the state transition depends on the dispatched actions.
- Updating State Across Components: Use useReducer when you need to update state that is shared across multiple components.
How to Use useReducer:
- Import the Hook: Import the useReducer hook from React
- Define a Reducer Function: Define a reducer function that specifies how the state should be updated based on the dispatched action.
- Invoke useReducer with Reducer and Initial State: Call useReducer and provide the reducer function and the initial state as arguments.
Here's an example of how to use useReducer to manage a counter:
import React, { useReducer } from 'react'
const initialState = { count: 0 };
const reducer = (state, action) => { switch (action.type) { case 'INCREMENT': return { count: state.count + 1 }; case 'DECREMENT': return { count: state.count - 1 }; default: throw new Error('Unknown action type'); }};
const Counter = () => { const [state, dispatch] = useReducer(reducer, initialState);
const increment = () => { dispatch({ type: 'INCREMENT' }); };
const decrement = () => { dispatch({ type: 'DECREMENT' }); };
return ( <div> <p>Count: {state.count}</p> <button onClick={increment}>Increment</button> <button onClick={decrement}>Decrement</button> </div> );};
export default Counter;