How to update an object with setState in ReactJS?

In React, state objects store component data that can change over time. This tutorial covers how to update state objects using both class components with setState() and functional components with hooks.

Using setState() in Class Components

The setState() method is used to update state in class components. When updating nested objects, use the spread operator to preserve other properties.

Syntax

this.setState({
  student: {
    ...this.state.student,
    fees: new_value,
  },
});

Example: Updating Simple State Object

This example shows how to update a simple state property containing a random number:

import React, { Component } from "react";

class App extends Component {
  state = {
    number: Math.random(),
  };

  changeNumber = () => {
    this.setState({ number: Math.random() });
  };

  render() {
    return (
      <div>
        <h2>
          Generating random numbers with <i>setState()</i>
        </h2>
        <h3
          style={{
            border: "2px solid yellow",
            borderRadius: "10px",
            width: "22rem",
            height: "5rem",
            backgroundColor: "blue",
            color: "white",
            fontSize: "2rem",
            padding: "1rem",
            textAlign: "center"
          }}
        >
          {this.state.number.toFixed(4)}
        </h3>
        <button
          onClick={this.changeNumber}
          style={{
            border: "2px solid green",
            borderRadius: "10px",
            padding: "0.5rem 1rem",
            backgroundColor: "yellow",
            color: "black",
            fontSize: "1rem",
          }}
        >
          Generate Random Number
        </button>
      </div>
    );
  }
}

export default App;

Example: Updating Nested Objects

When updating nested objects, use the spread operator to preserve unchanged properties:

import React, { Component } from "react";

class App extends Component {
  state = {
    student: {
      id: "123qwe",
      name: "Shubham",
      age: 22,
      fees: 200000,
    },
  };

  changeFees = () => {
    this.setState({
      student: {
        ...this.state.student,
        fees: this.state.student.fees + this.state.student.fees * 0.2,
      },
    });
  };

  render() {
    return (
      <div>
        <h2>
          Updating nested objects with <i>setState()</i>
        </h2>
        <div style={{ margin: "1rem 0" }}>
          <p><strong>Student ID:</strong> {this.state.student.id}</p>
          <p><strong>Name:</strong> {this.state.student.name}</p>
          <p><strong>Age:</strong> {this.state.student.age}</p>
          <p><strong>Fees:</strong> ${this.state.student.fees.toLocaleString()}</p>
        </div>
        <button
          onClick={this.changeFees}
          style={{
            border: "2px solid green",
            borderRadius: "10px",
            padding: "0.5rem 1rem",
            backgroundColor: "yellow",
            color: "black",
            fontSize: "1rem",
          }}
        >
          Increase Fees by 20%
        </button>
      </div>
    );
  }
}

export default App;

Using useState Hook in Functional Components

React hooks provide a modern way to manage state in functional components. The useState hook is the recommended approach for new React applications.

Syntax

const [state, setState] = useState({
  prop1: "Value1",
  prop2: "value2",
  prop3: "value3",
});

setState(prevState => ({ ...prevState, prop3: newValue }));

Example: Interactive State Update

This example demonstrates updating state based on user input using hooks:

import React, { useState } from "react";

const App = () => {
  const [state, setState] = useState({
    prop1: "Value1",
    prop2: "Value2",
    prop3: "Value3",
  });
  const [inputValue, setInputValue] = useState("");

  function handleInputChange(e) {
    setInputValue(e.target.value);
  }

  function handleSubmit() {
    setState(prevState => ({ ...prevState, prop3: inputValue }));
    setInputValue(""); // Clear input after submit
  }

  return (
    <div style={{ padding: "1rem" }}>
      <h2>
        Using <i>useState</i> hooks to update state objects
      </h2>
      
      <div style={{ margin: "1rem 0" }}>
        <h3>Current State:</h3>
        <div style={{ color: "blue", fontSize: "1.2rem" }}>
          prop1: {state.prop1} | prop2: {state.prop2} | prop3: {state.prop3}
        </div>
      </div>

      <div style={{ margin: "1rem 0" }}>
        <h3>Update prop3:</h3>
        <input 
          type="text" 
          value={inputValue} 
          onChange={handleInputChange}
          placeholder="Enter new value for prop3"
          style={{
            padding: "0.5rem",
            margin: "0.5rem",
            border: "1px solid #ccc",
            borderRadius: "4px"
          }}
        />
        <button
          onClick={handleSubmit}
          disabled={!inputValue.trim()}
          style={{
            margin: "0.5rem",
            padding: "0.5rem 1rem",
            backgroundColor: inputValue.trim() ? "lightgreen" : "#ccc",
            border: "2px dotted blue",
            borderRadius: "10px",
            color: "black",
            fontSize: "1rem",
            cursor: inputValue.trim() ? "pointer" : "not-allowed"
          }}
        >
          Update State
        </button>
      </div>
    </div>
  );
};

export default App;

Key Differences

Aspect Class Component (setState) Functional Component (useState)
Syntax this.setState({...}) setState(prevState => {...})
Component Type Class components only Functional components
Modern Approach Legacy (still supported) Recommended for new projects
Bundle Size Larger Smaller

Best Practices

  • Always use the spread operator when updating nested objects
  • Prefer functional updates when the new state depends on the previous state
  • Use useState hook for new React applications
  • Keep state updates immutable - never modify state directly

Conclusion

Both setState() in class components and useState hook in functional components allow updating state objects. The hooks approach is recommended for modern React development due to its simplicity and better performance.

Updated on: 2026-03-15T23:19:01+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements