DEV Community

Discussion on: My 5 cents about React Hooks

Collapse
 
drewkiimon profile image
Andrew Pagan

The only thing I don't get is the following line with hooks

handleChange = (name, value) => setData(prev => ({ ...prev, [name]: value }))

I have to sometimes do this in useEffect to set a value properly. What exactly are we doing? Just using the previous value? When do you know when to do it exactly?

Collapse
 
guilhermetoti profile image
Guilherme Toti

When you use call the setter with a function as parameter, like you did, the “prev” (the function argument) is the current state.
In your example, the “prev” is the current value of “data”.
You usually do that way instead of just setData(something) when you probably have state changes with a very short period and you want to make sure you are using the latest state value possible.
As setState is async, you may call it before other state change be completed and use old values. Using it with a parameter grants you using the latest state.

Collapse
 
drewkiimon profile image
Andrew Pagan

That makes sense thank you! :)