React js Updating Objects in State Practice Questions with Solutions

Introduction

Objects are commonly used in React state to store related information such as user profiles, products, settings, and form data. When updating an object in state, you should create a new object instead of directly changing the existing one. In this chapter, we will practice updating object properties using useState(), the spread operator, event handlers, and practical form examples. React js Updating Objects in State practice questions with solutions help to understand the concepts.

1. How do you Store an Object in React State?

You can use useState() to store an object in React state.

Solution:

import { useState } from "react";

function App() {
  const [user, setUser] = useState({
    name: "Rahul",
    age: 22,
    city: "Delhi"
  });

  return (
    <div>
      <h2>{user.name}</h2>
      <p>Age: {user.age}</p>
      <p>City: {user.city}</p>
    </div>
  );
}

export default App;

Here, the user state contains multiple related properties.


2. How do you Update One Property of an Object in React State?

Use the object spread operator to keep the existing properties and update the required property.

Solution:

import { useState } from "react";

function App() {
  const [user, setUser] = useState({
    name: "Rahul",
    age: 22,
    city: "Delhi"
  });

  function updateName() {
    setUser((currentUser) => ({
      ...currentUser,
      name: "Amit"
    }));
  }

  return (
    <div>
      <p>Name: {user.name}</p>

      <button onClick={updateName}>
        Update Name
      </button>
    </div>
  );
}

export default App;

The expression:

{
  ...currentUser,
  name: "Amit"
}

creates a new object while keeping the other properties unchanged.


3. How do you Update Multiple Properties of an Object?

You can update multiple properties in the same state update.

Solution:

import { useState } from "react";

function App() {
  const [user, setUser] = useState({
    name: "Rahul",
    age: 22,
    city: "Delhi"
  });

  function updateUser() {
    setUser((currentUser) => ({
      ...currentUser,
      name: "Amit",
      age: 25,
      city: "Mumbai"
    }));
  }

  return (
    <div>
      <p>Name: {user.name}</p>
      <p>Age: {user.age}</p>
      <p>City: {user.city}</p>

      <button onClick={updateUser}>
        Update User
      </button>
    </div>
  );
}

export default App;

Only the properties specified in the new object are replaced.


4. How do you Update an Object Property using a Previous State Value?

When the new value depends on the previous state, use the functional updater form.

Solution:

import { useState } from "react";

function App() {
  const [user, setUser] = useState({
    name: "Rahul",
    age: 22
  });

  function increaseAge() {
    setUser((currentUser) => ({
      ...currentUser,
      age: currentUser.age + 1
    }));
  }

  return (
    <div>
      <p>
        {user.name} is {user.age} years old.
      </p>

      <button onClick={increaseAge}>
        Increase Age
      </button>
    </div>
  );
}

export default App;

Here:

age: currentUser.age + 1

uses the previous age to calculate the new age.


5. How do you Update an Object using an Input Field?

You can connect an input field to an object in state and update its property through onChange.

Solution:

import { useState } from "react";

function App() {
  const [user, setUser] = useState({
    name: "",
    email: ""
  });

  function handleNameChange(event) {
    setUser((currentUser) => ({
      ...currentUser,
      name: event.target.value
    }));
  }

  return (
    <div>
      <input
        type="text"
        value={user.name}
        onChange={handleNameChange}
        placeholder="Enter name"
      />

      <p>Name: {user.name}</p>
    </div>
  );
}

export default App;

The input value comes from React state, and onChange updates the object.


6. How do you Update Multiple Object Properties using One Event Handler?

You can use the input’s name attribute to update different object properties using the same handler.

Solution:

import { useState } from "react";

function App() {
  const [user, setUser] = useState({
    name: "",
    email: "",
    city: ""
  });

  function handleChange(event) {
    const { name, value } = event.target;

    setUser((currentUser) => ({
      ...currentUser,
      [name]: value
    }));
  }

  return (
    <div>
      <input
        name="name"
        value={user.name}
        onChange={handleChange}
        placeholder="Name"
      />

      <input
        name="email"
        value={user.email}
        onChange={handleChange}
        placeholder="Email"
      />

      <input
        name="city"
        value={user.city}
        onChange={handleChange}
        placeholder="City"
      />

      <p>Name: {user.name}</p>
      <p>Email: {user.email}</p>
      <p>City: {user.city}</p>
    </div>
  );
}

export default App;

The computed property:

[name]: value

updates the property whose name matches the input’s name attribute.


7. How do you Update a Nested Object in React State?

For nested objects, you need to copy each object level that you are changing.

Solution:

import { useState } from "react";

function App() {
  const [user, setUser] = useState({
    name: "Rahul",
    address: {
      city: "Delhi",
      country: "India"
    }
  });

  function updateCity() {
    setUser((currentUser) => ({
      ...currentUser,
      address: {
        ...currentUser.address,
        city: "Mumbai"
      }
    }));
  }

  return (
    <div>
      <p>Name: {user.name}</p>
      <p>City: {user.address.city}</p>

      <button onClick={updateCity}>
        Change City
      </button>
    </div>
  );
}

export default App;

The important part is:

address: {
  ...currentUser.address,
  city: "Mumbai"
}

This keeps the existing country property while changing only city.


8. How do you Update a Boolean Property in an Object?

You can use the previous value to toggle a Boolean property.

Solution:

import { useState } from "react";

function App() {
  const [user, setUser] = useState({
    name: "Rahul",
    isOnline: false
  });

  function toggleStatus() {
    setUser((currentUser) => ({
      ...currentUser,
      isOnline: !currentUser.isOnline
    }));
  }

  return (
    <div>
      <p>
        Status: {user.isOnline ? "Online" : "Offline"}
      </p>

      <button onClick={toggleStatus}>
        Change Status
      </button>
    </div>
  );
}

export default App;

The expression:

!currentUser.isOnline

changes true to false and false to true.


9. Why Should You Avoid Directly Modifying an Object in React State?

You should avoid changing the existing state object directly.

For example, avoid:

user.name = "Amit";
setUser(user);

This mutates the existing object.

Instead, create a new object:

setUser((currentUser) => ({
  ...currentUser,
  name: "Amit"
}));

This approach treats the previous state as immutable and makes the state update predictable.

The same principle applies to nested objects: copy the object levels that need to change rather than mutating them directly.


10. How do you Build a Practical User Profile Form using Object State?

You can store all profile information inside one object and update the fields with a single event handler.

Solution:

import { useState } from "react";

function ProfileForm() {
  const [profile, setProfile] = useState({
    name: "",
    email: "",
    city: "",
    age: ""
  });

  function handleChange(event) {
    const { name, value } = event.target;

    setProfile((currentProfile) => ({
      ...currentProfile,
      [name]: value
    }));
  }

  function handleSubmit(event) {
    event.preventDefault();

    console.log(profile);
  }

  return (
    <form onSubmit={handleSubmit}>
      <h2>User Profile</h2>

      <input
        type="text"
        name="name"
        value={profile.name}
        onChange={handleChange}
        placeholder="Enter name"
      />

      <br /><br />

      <input
        type="email"
        name="email"
        value={profile.email}
        onChange={handleChange}
        placeholder="Enter email"
      />

      <br /><br />

      <input
        type="text"
        name="city"
        value={profile.city}
        onChange={handleChange}
        placeholder="Enter city"
      />

      <br /><br />

      <input
        type="number"
        name="age"
        value={profile.age}
        onChange={handleChange}
        placeholder="Enter age"
      />

      <br /><br />

      <button type="submit">
        Save Profile
      </button>

      <h3>Profile Preview</h3>

      <p>Name: {profile.name}</p>
      <p>Email: {profile.email}</p>
      <p>City: {profile.city}</p>
      <p>Age: {profile.age}</p>
    </form>
  );
}

export default ProfileForm;

What this example demonstrates:

Object state:

const [profile, setProfile] = useState({
  name: "",
  email: "",
  city: "",
  age: ""
});

Updating the object:

setProfile((currentProfile) => ({
  ...currentProfile,
  [name]: value
}));

Reading object properties:

profile.name
profile.email
profile.city
profile.age

This pattern is useful for registration forms, profile forms, checkout forms, settings pages, and dashboard forms.

Key Takeaways

  • Objects can store multiple related values in React state.
  • Use useState() to create object state.
  • Use the spread operator to create a new object when updating state.
  • Do not directly mutate an object stored in state.
  • Use a functional state updater when the new value depends on the previous state.
  • Computed property names such as [name]: value are useful for handling multiple form fields.
  • Nested objects require copying each level that you are changing.
  • Boolean properties can be toggled using the previous state value.
  • Object state is commonly used for forms, profiles, products, settings, and user data.
  • Treating state as immutable makes React state updates more predictable.

FAQs

1. How do you update an object in React state?

Use the state setter with the object spread operator:

setUser((currentUser) => ({
  ...currentUser,
  name: "Amit"
}));

2. Can I directly change a property of a React state object?

You should not directly mutate the existing state object. Instead, create a new object containing the updated property.

3. Why is the spread operator used when updating objects?

The spread operator copies the existing properties into a new object, allowing you to replace only the properties that need to change.

4. How do you update nested objects in React?

Copy the outer object and the nested object that you are changing.

setUser((currentUser) => ({
  ...currentUser,
  address: {
    ...currentUser.address,
    city: "Mumbai"
  }
}));

5. How do you update multiple properties in an object?

You can include multiple properties in the new object:

setUser((currentUser) => ({
  ...currentUser,
  name: "Amit",
  age: 25
}));

6. How do you update form fields stored in an object?

Use an onChange handler and the input’s name attribute:

setForm((currentForm) => ({
  ...currentForm,
  [name]: value
}));

7. When should you use a functional state updater?

Use it when the new state depends on the previous state. For example:

setUser((currentUser) => ({
  ...currentUser,
  age: currentUser.age + 1
}));

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top