Posts

`useReducer` is like `useState`, but in a more organized form.

0 comments·0 reblogs
sawsenbenkhadhr
60
·
0 views
·
1 min read

useReducer is like useState, but in a more organized form.

With useState, you update the state directly—for example, by calling setCounter(counter + 1).

With useReducer, you don’t change the state yourself. Instead, you send an instruction, and a separate function decides how the state should be updated.

It consists of three parts:

  1. The state: This is your data—e.g., { counter: 0 }.

  2. The dispatch: This acts as a button that sends an instruction—e.g., dispatch({ type: 'INCREMENT' }). You simply specify "what should be done."

  3. The reducer: This is the "boss." It’s a function that takes the current state and the instruction, then returns the new state.
    // The boss
    function reducer(state, action) {
    if (action.type === 'INCREMENT') {
    return { counter: state.counter + 1 };
    }
    if (action.type === 'DECREMENT') {
    return { counter: state.counter - 1 };
    }
    return state;
    }
    // Inside your component
    const [state, dispatch] = useReducer(reducer, { counter: 0 });
    When should you use it?
    useState is sufficient for 90% of cases—like handling a boolean or an input field.
    useReducer becomes useful when:
    your state is a complex object;
    there are many different ways to modify it;
    the next value depends on the previous one.
    In short: useState means "set this value," while useReducer means "here is what happened—figure out how to update the state accordingly."
    Image from thread

Posted Using INLEO