Unlike the state from classes, you are not limited to a single object. With useState, you can create separate values for each case like this:
const [name, setName] = useState('John');
const [email, setEmail] = useState('john@example.com');
const [age, setAge] = useState(25);
But, I found this very dirty and prefer using only one useState initialized with an object:
const [user, setUser] = useState(
{ name: 'John', email: 'john@example.com', age: 25 }
);
I understand that there is no strict limit and useState can store objects, but in class components, when you update state using this.setState, it is merged with the old one. With useState, the update function replaces the old state with a new one (there is no merging).
I frequently implemented like below:
setUser(prevStat => ({
...prevState,
name: 'Daniel'
}));
If I'm correct, updating an object state will re-render all fields of the object state, which supposedly will be more expensive for the app?
- Am I correct with this approach?