MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Updating State and Immutable Updates0%
Study Materials
React.js for BeginnersProgress 0%
1.1Why React and Single-Page Architecture1.2Setting Up Modern React with Vite1.3React Project Directory Structure and Entry Points1.4Virtual DOM and React Render Cycle Explained
4.1Introduction to Component State4.2The useState Hook Fundamentals4.3Updating State and Immutable Updates4.4Lifting State Up Between Siblings
HomeTutorialsReact.js for BeginnersUpdating State and Immutable Updates
Lifting State Up Between Siblings

Updating State and Immutable Updates

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

1. The Rule of Immutability

In React, state should be treated as immutable (read-only). You must never modify existing state objects or arrays directly in place. Instead, always replace them with a fresh copy containing the desired changes.

1// ❌ Direct Mutation: FORBIDDEN!
2const [user, setUser] = useState({ name: 'Rohit', age: 24 });
3user.age = 25; // Direct mutation does NOT change object reference!
4setUser(user); // React sees same reference (Object.is) -> NO RE-RENDER!
5 
6// ✅ Immutable Update: Create a new object copy
7setUser({
8 ...user, // Copy existing properties using object spread
9 age: 25 // Overwrite specific property
10});

Because React uses reference equality (Object.is) to detect state changes, mutating an existing object or array in place preserves the same memory address. React assumes nothing has changed and bails out of re-rendering.

2. Functional State Updates (Updater Functions)

State updates are batched and asynchronous. If your new state depends on the immediately preceding state, you should pass a callback function to your state setter instead of a raw value:

1const [count, setCount] = useState(0);
2 
3function handleMultipleIncrements() {
4 // ❌ Problematic: All three calls read 'count' as 0 in the current closure!
5 // setCount(count + 1); // 0 + 1 = 1
6 // setCount(count + 1); // 0 + 1 = 1
7 // setCount(count + 1); // 0 + 1 = 1
8 // Result: count becomes 1, NOT 3!
9 
10 // ✅ Correct: Functional updates guarantee access to the latest pending state
11 setCount(prevCount => prevCount + 1);
12 setCount(prevCount => prevCount + 1);
13 setCount(prevCount => prevCount + 1);
14 // Result: count correctly becomes 3!
15}

3. Immutably Updating Arrays in State

Arrays in JavaScript are reference types. When adding, removing, or modifying array elements in state, use non-mutating array methods:

Action❌ Mutating (Avoid)✅ Immutable (Preferred)
Add itemarr.push(item), arr.unshift(item)[...arr, item] or [item, ...arr]
Remove itemarr.splice(index, 1), arr.pop()arr.filter(item => item.id !== id)
Update itemarr[index] = newValuearr.map(item => item.id === id ? { ...item, ...newValue } : item)
Sort / Reversearr.sort(), arr.reverse()[...arr].sort(), [...arr].reverse()

Concrete Array Update Examples:

1const [todos, setTodos] = useState([
2 { id: 1, text: 'Master React JSX', completed: true },
3 { id: 2, text: 'Learn useState Hook', completed: false }
4]);
5 
6// 1. Adding a new todo:
7const addTodo = (newText) => {
8 const newTodo = { id: Date.now(), text: newText, completed: false };
9 setTodos(prev => [...prev, newTodo]);
10};
11 
12// 2. Toggling completion status:
13const toggleTodo = (id) => {
14 setTodos(prev => prev.map(todo =>
15 todo.id === id ? { ...todo, completed: !todo.completed } : todo
16 ));
17};
18 
19// 3. Deleting a todo:
20const deleteTodo = (id) => {
21 setTodos(prev => prev.filter(todo => todo.id !== id));
22};

4. Immutably Updating Nested Objects

When updating nested objects, remember that the object spread operator (...) only performs a shallow copy. Nested objects must be explicitly copied at every level of depth:

1const [student, setStudent] = useState({
2 name: 'Kavita',
3 contact: {
4 email: 'kavita@example.com',
5 city: 'New Delhi'
6 }
7});
8 
9// Updating nested city property immutably:
10setStudent(prev => ({
11 ...prev,
12 contact: {
13 ...prev.contact,
14 city: 'Bengaluru'
15 }
16}));

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
Why does direct mutation of an object in React state (e.g. user.name = 'New'; setUser(user);) often fail to trigger a re-render?
Question 2
When should you pass a callback function (e.g. setCount(prev => prev + 1)) to a state setter?
Question 3
Which array method is recommended for removing an item from state without mutating the original array?
Question 4
How do you add an item to the end of an array stored in state using the spread operator?
Question 5
What is a key limitation of the spread operator (...) when copying objects with nested properties?
Next Lesson

Lifting State Up Between Siblings

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
The useState Hook FundamentalsLifting State Up Between Siblings

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master React.js for Beginners with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext