React ~ Hooks ~ Managing (Complex) State - rohit120582sharma/Documentation GitHub Wiki

useReducer is a hook that is used for state management. It is an alternative to useState which is built using useReducer.

If you have any business logic for data transmission/manipulation, then go with useReducer intead of useState.

If different pieces of state update independently from one another, useState should work fine. If your state tends to be updated together or if updating one piece of state is based on another piece of state, go with useReducer.


import React from 'react';

const initialState = {
    counter: 0
};
const reducer = (state, action) => {
    switch(action.type) {
        case 'increment':
            return {counter: state.counter + 1};
        case 'decrement':
            return {counter: state.counter - 1};
        case 'reset':
            return initialState;
        default:
            return state;
    }
}

const Counter = () => {
    const [count, dispatch] = React.useReducer(reducer, initialState);

    return (
        <div>
            <button onClick={() => dispatch({type: 'increment'})}>Increment</button>
            <button onClick={() => dispatch({type: 'decrement'})}>Decrement</button>
            <button onClick={() => dispatch({type: 'reset'})}>Reset</button>
            <p>Count: {count.counter}</p>
        </div>
    );
}
⚠️ **GitHub.com Fallback** ⚠️