DEV Community

Cover image for Why useReducer? Why do we need multiple functions to update a single state?
Megalraja
Megalraja

Posted on

Why useReducer? Why do we need multiple functions to update a single state?

When working with React, we usually use useState() to manage state.

For example, imagine building a counter application with three operations:

  • Increment
  • Decrement
  • Reset

Using useState(), we might write separate functions for each operation.

Using useState()

const [count, setCount] = useState(0);

function increment() {
    setCount(count + 1);
}

function decrement() {
    setCount(count - 1);
}

function reset() {
    setCount(0);
}
Enter fullscreen mode Exit fullscreen mode

Here, we have three different functions to perform three operations on the same state.

This is perfectly fine for a small application. But imagine having many actions and more complex state update logic. Managing all those functions can become difficult.

What if we use useReducer()?

Instead of creating separate functions for every operation, we can define the state update logic in one reducer function.

function reducer(state, action) {
    switch (action.type) {
        case 'increment':
            return state + 1;

        case 'decrement':
            return state - 1;

        case 'reset':
            return 0;

        default:
            return state;
    }
}
Enter fullscreen mode Exit fullscreen mode

Now we can trigger different operations using dispatch().

const [count, dispatch] = useReducer(reducer, 0);

<button onClick={() => dispatch({type: 'increment'})}>
    Increment
</button>

<button onClick={() => dispatch({type: 'decrement'})}>
    Decrement
</button>

<button onClick={() => dispatch({type: 'reset'})}>
    Reset
</button>
Enter fullscreen mode Exit fullscreen mode

What is the actual difference?

With useState(), we write separate functions to handle different state updates.

With useReducer(), we keep the state update logic in one place and send different actions through dispatch().

Important: We don't always need useReducer(). For simple state updates, useState() is easier. When state logic becomes complex, useReducer() helps organize the code.

Conclusion

The main advantage of useReducer() is not reducing the number of functions. It is organizing multiple state update operations in one reducer function.

Both hooks are useful. The choice depends on the complexity of your application.

One important concept to remember: useReducer() doesn't eliminate functions. It replaces multiple state-update handlers with one centralized reducer function, while dispatch() tells it which action to perform.

Top comments (0)