Open In App

How to Update Nested State Properties in ReactJS?

Last Updated : 03 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Updating Nested State Properties in React is an important part of State Management. Nested states are objects containing one or more properties as arrays and objects.

Prerequisites:

How to Updated Nested State in React

To update nested state in React we can use the spread operator, callback with setState, or external libraries like immer and immutability-helper. Below are the example to update nested state with spread operator.

Steps to Create React Application

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Project Structure: It will look like the following.

Project Structure

Approach 1: Using Class Components

We can create a dummy object to perform operations on it (update properties that we want) then replace the component’s state with the updated object.

Example: In this example, the spread operator is used to create a copy of the nested address object, allowing the city property to be updated immutably.

JavaScript
// Filename: App.js

import React, { Component } from "react";
class App extends Component {
	// Nested object
	state = {
		name: "GeeksforGeeks",
		address: {
			colony: "Sector 136",
			city: "Noida",
			state: "Uttar Pradesh"
		}
	};

	handleUpdate = () => {
		// Creating a dummy object using spread operator
		var address = { ...this.state.address };

		// Updating the city
		address.city = "Gautam Budha Nagar";
		this.setState({ address });
	};

	render() {
		return (
			<div style={{ margin: 200 }}>
				<h1>{this.state.name}</h1>
				<h1>
					{this.state.address.colony} {", "}
					{this.state.address.city}
					{", "}
					{this.state.address.state}
				</h1>
				<button onClick={this.handleUpdate}>UpdateCity </button>
			</div>
		);
	}
}

export default App;

Approach 2: Using Functional Component

We can pass the old nested object using the spread operator and then override the particular properties of the nested object. We will be using the React Hooks to access the state in functional component.

Example: In this example, spread operator creates shallow copies of objects, enabling you to update nested state properties without mutating the original state.

JavaScript
// Filename: App.js

import React, { useState } from "react";

const App = () => {
	// Initializing state using useState hook
	const [state, setState] = useState({
		name: "GeeksforGeeks",
		address: {
			colony: "Sector 136",
			city: "Noida",
			state: "Uttar Pradesh"
		}
	});

	const handleUpdate = () => {
		// Overriding the city property of address object
		setState((prevState) => ({
			...prevState,
			address: { ...prevState.address, city: "Gautam Budha Nagar" }
		}));
	};

	return (
		<div style={{ margin: 200 }}>
			<h1>{state.name}</h1>
			<h1>
				{state.address.colony}, {state.address.city},{" "}
				{state.address.state}
			</h1>
			<button onClick={handleUpdate}>UpdateCity</button>
		</div>
	);
};

export default App;

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output:

output---update-nested-state-in-react




Next Article

Similar Reads