Reputation: 1903
I'm working on a functional React component using the useState()
hook. I'm a little confused by either the way this hook should be used or the design decisions behind it.
I made a codepen example to illustrate my question:
https://codepen.io/svenvandescheur/pen/ewwBwR
Class based component
In a class based component, this.setState({foo: 'bar'})
updated the state with only the keys in in the object passed to the first arguments. If the state already contained different values, those were left in place.
Functional component
I falsely assumed that the syntax and behavior of setState()
provided by useState()
would be very similar to its counterpart provided by Component
. However, I noticed that setState({foo: 'bar'})
would replace the entire state, removing keys that were not passed.
This issue can be addressed by passing the entire state on every call to setState()
using a spread operator, then adding the the changes afterwards, like so: setState({...state, foo: 'bar'})
.
This feels very repetitive, and in my real world scenario even caused a bug where new state was overriden with old state.
My question, is whether I'm understanding useState()
from both Component
as useState()
correctly, and why this behavior was chosen. And what is the currently the preferred way of dealing with state in React.
Upvotes: 0
Views: 211
Reputation: 6253
Your understanding is correct. setState
will merge current state and new state together to create a new state. useState
will take the given value and replace old state.
This behaviour might seem unintuitive, but allows for primitive values to be used as state such as strings, numbers and booleans.
If you need more state you can simply add more useState
's. And if your state update logic becomes more than a little complex you should use useReducer
.
Upvotes: 1