Open In App

How to use useReducer within a custom hook?

useReducer is one of the fundamental built-in hooks in React, primarily used for managing complex state logic within functional components. Using useReducer within a custom hook is quite similar to using it in a regular functional component.

Understanding the concept of useReducert within a custom hook:

Example: Below is an example of using useReducer within a custom hook.




import React from 'react';
import useCounter from './components/useCounter';
 
 
const CounterComponent = () => {
    // Use the custom hook to get state and dispatch function
    const { count, increment, decrement } = useCounter(0);
 
    return (
        <div>
            <h1>Counter App</h1>
            <span>{count}</span><br></br>
            <button onClick={increment}>Increment</button>
            <button onClick={decrement}>Decrement</button>
        </div>
    );
};
 
export default CounterComponent;




import { useReducer } from 'react';
 
// Define your reducer function
const reducer = (state, action) => {
    switch (action.type) {
        case 'INCREMENT':
            return { count: state.count + 1 };
        case 'DECREMENT':
            return { count: state.count - 1 };
        default:
            return state;
    }
};
 
// Define your custom hook
const useCounter = (initialCount) => {
    // Call useReducer inside your custom hook
    const [state, dispatch] = useReducer(reducer,
        { count: initialCount });
 
    // Return state and dispatch from the custom hook
    return {
        count: state.count, increment:
            () => dispatch({ type: 'INCREMENT' }),
        decrement: () => dispatch({ type: 'DECREMENT' })
    };
};
 
export default useCounter;

Output:

Output


Article Tags :