DEV Community

3 Reasons to useReducer() over useState()

Linas Spukas on August 18, 2019

What It Is useReducer() is a method from the React Hooks API, similar to useState but gives you more control to manage the state. It tak...
Collapse
 
clarity89 profile image
Alex K.

For the first point you can still use State's hook functional form: setState(state => state + 1).

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
neoprint3d profile image
Drew Ronsman

Explain

Collapse
 
joelmarkbyrd profile image
Joel Byrd

The first point says to use useReducer() when the next state depends on the previous one - he uses a counter as an example, where the next state is one more than the previous state. The point @clarity89 is making is that the useState() setter function provides a format that gives you access to the previous value in a way that gives you a predictable state transition, so useReducer() is not necessary in this case. You can read the documentation here, but basically the form is (using the counter example):

setState(prevCounterValue => prevCounterValue + 1)

So basically the first point is invalid, because useReducer() is not necessary to provide a predictable state transition when the next value depends on the previous value.

Collapse
 
aisone profile image
Aaron Gong

Why?

Collapse
 
kiszuriwalilibori profile image
Piotr Maksymiuk

What you mean?

Collapse
 
geisonmcd profile image
Geison • Edited

I have a screen where I show a list of (school) exams. When I click in one it navigates to another page where I can edit each exam field.

In this page I created a state for each single exam field (name, code, max weight, start date, end date, etc). Is this a case where I should've used a reducer? I also could create a state with the whole exam object right?

It's not clear to me the reducer advantage in my example.

Collapse
 
affkar profile image
Karthick

the component for the second page or the second component should just accept the exam as a prop.

Collapse
 
klmlab profile image
klm

Very Nice, Thank You

Collapse
 
mantenn profile image
Nazar Maksymchuk

not many benefits to reducer, I can still as easily test my state functions. by having the state handler be outside of the component.

Collapse
 
limpuls profile image
Laimis Petravicius

Always coming back to this when I need a reminder. Very well written!

Collapse
 
itscosmo profile image
Paul Kleimeyer

Very on point and well-written article. Thank you.

Collapse
 
mshez profile image
Muhammad Shahzad

Nice piece. userReducer is always recommended when state is bigger and complex.

Collapse
 
karthiganesan90 profile image
Karthikeyan Ganesan

Cool explanation, Thanks for the short crisp & clear note.