State Immutability
Learn why React state should be treated as read-only, understand mutable and immutable updates, and use the spread operator, map(), and filter() to update state safely.
1. What Is State Immutability?
Immutability means creating a new value instead of directly modifying an existing value. In React, we should treat state as read-only and use the state setter to provide an updated value.
For example, if CIIT Training Institute maintains a list of students, we should create a new array when adding or removing a student instead of modifying the existing state array.
const students = [
"SAMADHAN",
"SAMIKSHA",
"PRADNYA"
];
// Create a new array
const updatedStudents = [
...students,
"ROHAN"
];
The original array remains unchanged. The new array contains the original students and the additional student.
2. Mutable vs Immutable Updates
A mutable update modifies an existing array or object. An immutable update creates a new array or object containing the required changes.
students
students.push("ROHAN")
students
[...students, "ROHAN"]
3. Directly Mutating State
Mutating state means directly changing an existing array or object stored in React state. This should be avoided because the reference may remain unchanged, and React may skip the expected re-render when the same value is passed back.
import { useState } from "react";
function StudentList() {
const [students, setStudents] = useState([
"SAMADHAN",
"SAMIKSHA",
"PRADNYA"
]);
function addStudent() {
students.push("ROHAN");
setStudents(students);
}
return (
<div>
<h2>CIIT Student List</h2>
<button onClick={addStudent}>
Add Student
</button>
<ul>
{students.map((student, index) => (
<li key={`${student}-${index}`}>
{student}
</li>
))}
</ul>
</div>
);
}
export default StudentList;
push()modifies the existing array.- The original state array is changed directly.
- The same array reference is passed to the setter.
- React may skip the expected re-render because the reference has not changed.
4. Updating Arrays Immutably
The spread operator creates a new array containing the existing items. We can add a new item without modifying the original state array.
import { useState } from "react";
function StudentList() {
const [students, setStudents] = useState([
"SAMADHAN",
"SAMIKSHA",
"PRADNYA"
]);
function addStudent() {
setStudents((previousStudents) => [
...previousStudents,
"ROHAN"
]);
}
return (
<div>
<h2>CIIT Student List</h2>
<button onClick={addStudent}>
Add Student
</button>
<ul>
{students.map((student, index) => (
<li key={`${student}-${index}`}>
{student}
</li>
))}
</ul>
</div>
);
}
export default StudentList;
How Does It Work?
- The button calls the
addStudent()function. - The functional updater receives the previous state.
- The spread operator copies the existing array items.
- The new student is added to the new array.
- React receives the new state and updates the interface.
Expected Browser Output
- SAMADHAN
- SAMIKSHA
- PRADNYA
- ROHAN
5. Updating Objects Immutably
React state can also contain objects. We should create a new object when updating a property instead of directly changing a property of the existing state object.
student.name = "SAMIKSHA";
setStudent(student);
This changes the existing object directly.
setStudent(previous => ({
...previous,
name: "SAMIKSHA"
}));
This creates a new object with the updated name.
import { useState } from "react";
function StudentObject() {
const [student, setStudent] = useState({
name: "SAMADHAN",
course: "React JS",
institute: "CIIT Training Institute"
});
function updateStudent() {
setStudent((previousStudent) => ({
...previousStudent,
name: "SAMIKSHA"
}));
}
return (
<div>
<h2>Student Details</h2>
<p>Name: {student.name}</p>
<p>Course: {student.course}</p>
<p>Institute: {student.institute}</p>
<button onClick={updateStudent}>
Update Student Name
</button>
</div>
);
}
export default StudentObject;
Name: SAMIKSHA
Course: React JS
Institute: CIIT Training Institute
6. Using map() and filter() Immutably
The map() and filter() methods
return new arrays. They are useful for updating or removing
items without modifying the original array.
Using map() to Update an Item
setStudents((previousStudents) =>
previousStudents.map((student) =>
student.id === 1
? { ...student, name: "SAMADHAN - React Student" }
: student
)
);
The matching student is replaced with a new object. All other students remain unchanged.
Using filter() to Remove an Item
setStudents((previousStudents) =>
previousStudents.filter(
(student) => student.id !== 2
)
);
The returned array contains every student except the student whose ID is 2.
map()creates a transformed array.filter()creates an array containing matching items.- Neither method mutates the original array when used in these examples.
7. Understanding the Spread Operator
The spread operator (...) expands the items of
an array or the properties of an object into a new array or
object.
const originalStudents = [
"SAMADHAN",
"SAMIKSHA"
];
const updatedStudents = [
...originalStudents,
"PRADNYA"
];
console.log(originalStudents);
console.log(updatedStudents);
originalStudents:
["SAMADHAN", "SAMIKSHA"]
updatedStudents:
["SAMADHAN", "SAMIKSHA", "PRADNYA"]
8. Common Mistakes
Using push() to Modify State
Avoid:
students.push("ROHAN");
Use:
setStudents(previous => [...previous, "ROHAN"]);
Changing an Object Property Directly
Avoid:
student.name = "SAMIKSHA";
Use:
setStudent(previous => ({
...previous,
name: "SAMIKSHA"
}));
Updating State Using a Stale Value
When the next state depends on the previous state, prefer a functional updater.
Recommended:
setCount(previousCount => previousCount + 1);
Assuming Spread Makes a Deep Copy
The spread operator copies only one level. When updating nested state, create new objects at every level that needs to change.
9. Practice Questions
- Explain state immutability in React.
- Why should we avoid using push() directly on a state array?
- Create a new array by adding a student using the spread operator.
- Remove a student using filter() without mutating the original array.
- Update a student's name using map().
- Update a student object using the spread operator.
- Explain the difference between a shallow copy and a deep copy.
Summary
State immutability means treating React state as read-only and creating new arrays or objects whenever an update is required. The spread operator helps copy existing values, map() is useful for updating array items, and filter() helps remove items. Avoid directly modifying state with methods such as push() or by changing object properties. When the next value depends on the previous state, use a functional state updater. These practices help make React applications more predictable and easier to maintain.