From the course: Build Modern Web Apps with React, Hooks, State Management, and APIs Using Vite or Next.js

Unlock this course with a free trial

Join today to access over 25,200 courses taught by industry experts.

Managing objects

Managing objects

Welcome back, in this video we'll see how we can use objects inside our useState hook. We know from the previous understanding that state updates must be immutable. We should never be updating the state directly or the state variable directly. This line here will give you a bit of revision that if user.name is a state value, we cannot set it directly. Instead, we have to use the setter function. But over here, our example is a slight different. Instead of having a string variable name, we have a user object. That means our useState value is actually an object, not a primary datatype such as number, string or boolean. Whenever we have to update an object inside our state using the setter function, we have to use the spread operator. The JavaScript useSpread operator gives us the advantage that we do not lose the rest of the object's fields but we only get to update whatever field we want to update. Consider this example. You have a user object which is part of your state and the…

Contents