Never mutate the object directly. Create a new object with the changes using the spread operator, like setUser({ ...user, name: 'New' }). React detects the new reference and re-renders.
How to Use useState to Update Your React UI
How do I update an object in useState?
The answer
More FAQs in How to Use useState to Update Your React UI
Call useState with an initial value. It returns the current state and a setter function. Call the setter with a new value to update state and trigger a re-render. Name the pair like count and setCount by convention.
Because state updates are asynchronous and batched. Reading the variable right after calling the setter shows the old value. React applies updates later and re-renders once, which improves performance.
When the new state depends on the previous state. Pass a function like setCount(prev => prev + 1) so you get the correct previous value, especially when multiple updates are batched together.
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.