DEV Community

Discussion on: My 5 cents about React Hooks

Collapse
pabloabc profile image
Pablo Berganza (he/him)

I've definitely enjoyed React much more since the introduction of Hooks!
Hey, I just have a minor nitpick! In your example of useState, you should generally avoid using an object. So instead of

const [data, setData] = useState({})

You could do something like this

const [name, setName] = useState('')
const [email, setEmail] = useState('')

Since (as you saw), setState does not merge objects by default, it just replaces the whole state.

Collapse
guilhermetoti profile image
Guilherme Toti Author

True, it replaces the whole state, but I do prefer to have an object on state instead N variables, (depending the case), but I think this is personal preferences.
When I set states with objects, I usually update it like (e.g):

setData(data => ({ ...data, someUpdate: “ok” });

This way I get the current state value, add it to my object, and update what I want on it... keeping it immutable.