To use the useReducer hook in React, you first need to import it at the top of your component file:
import React, { useReducer } from 'react';
Next, you can define your reducer function outside of your component, which will specify how state should be updated based on the action type. Here is an example of a simple reducer function:
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:
throw new Error();
}
}
Inside your component, you can use the useReducer hook by calling it with your reducer function and initial state:
const [state, dispatch] = useReducer(reducer, initialState);
The state
variable will hold the current state value, and dispatch
is a function that you can call to update the state by passing an action object with a type
property:
dispatch({ type: 'increment' });
You can then use the state
variable in your component to access the current state value, and update it by dispatching actions with the dispatch
function.
That's how you can use the useReducer hook in React to manage complex state logic in your components.