useEffect.dev
← Back to lessons

Lesson 11. Simplify state update logic with reducers 3. Should I use useState or useReducer?

Now you know reducers, you may wonder when you should use them instead of classic states provided by useState. Some developers always use useState since reducers can seem like much useless complexity.

I would say that reducers can be useful as soon as one of your components has several state attributes, and these states are linked to each other.

For instance, let’s imagine your state has two booleans, and you realize that it doesn’t make sense that the first one is false if the second one is true. Then maybe these states are dependent, and a reducer could reduce the complexity of the state updates.

It’s also the case when you notice that in a component you frequently update several state values at the same time. For instance:

const [first, setFirst] = useState(...)
const [second, setSecond] = useState(...)
const [third, setThird] = useState(...)
const [fourth, setFourth] = useState(...)
useEffect(() => {
setFirst(...)
setSecond(...)
setFourth(...)
fetch(...)
.then((res) => {
setSecond(...)
setThird(...)
setFourth(...)
})
}, [])
const callback = useCallback(() => {
setFirst(...)
setThird(...)
setFourth(...)
})

No doubt that the complexity of this kind of code can be improved using a reducer.