Updating State in React
Learn how to update React state using setter functions, understand why direct state mutation is incorrect, and explore practical examples using CIIT Training Institute's student and course scenarios.
1. What Does Updating State Mean?
Updating state means requesting a new value for information stored in a React component. When the value changes, React can render the component again to display the updated data.
For example, SAMADHAN has completed two React courses. After completing another course, the dashboard should display three completed courses.
import { useState } from "react";
function StudentProgress() {
const [completedCourses, setCompletedCourses] = useState(2);
function completeCourse() {
setCompletedCourses(completedCourses + 1);
}
return (
<div>
<h2>Student: SAMADHAN</h2>
<p>Completed Courses: {completedCourses}</p>
<button onClick={completeCourse}>
Complete Another Course
</button>
</div>
);
}
export default StudentProgress;
Expected Browser Output
Student: SAMADHAN
Initially: Completed Courses: 2
After clicking once: Completed Courses: 3
2. Updating State with a Setter Function
The setter function returned by useState requests an update to the state value. You can pass the next value directly when you already know what that value should be.
import { useState } from "react";
function StudentName() {
const [name, setName] = useState("SAMIKSHA");
function changeName() {
setName("PRADNYA");
}
return (
<div>
<h2>Student Name: {name}</h2>
<button onClick={changeName}>
Change Student Name
</button>
</div>
);
}
export default StudentName;
Explanation:
- The initial name is SAMIKSHA.
-
Clicking the button calls
changeName. -
setName("PRADNYA")requests the new name. - React renders the updated name.
Expected Browser Output
Before clicking: Student Name: SAMIKSHA
After clicking: Student Name: PRADNYA
3. Updating Number State
Number state is useful for counters, course progress, attendance totals, and the number of completed lessons.
import { useState } from "react";
function CourseCounter() {
const [lessonsCompleted, setLessonsCompleted] = useState(0);
return (
<div>
<h2>PRADNYA's Course Progress</h2>
<p>Lessons Completed: {lessonsCompleted}</p>
<button
onClick={() =>
setLessonsCompleted(lessonsCompleted + 1)
}
>
Complete Lesson
</button>
</div>
);
}
export default CourseCounter;
Expected Browser Output
Initially: Lessons Completed: 0
After one click: Lessons Completed: 1
After two clicks: Lessons Completed: 2
Each click requests an increment of the lesson count. React then displays the current value in the component.
4. Updating String State
String state can store names, course titles, messages, selected categories, and other text values.
import { useState } from "react";
function CourseStatus() {
const [status, setStatus] = useState("In Progress");
function completeCourse() {
setStatus("Completed");
}
return (
<div>
<h2>Student: SAMADHAN</h2>
<p>React Course Status: {status}</p>
<button onClick={completeCourse}>
Complete Course
</button>
</div>
);
}
export default CourseStatus;
Expected Browser Output
Initially: React Course Status: In Progress
After clicking: React Course Status: Completed
5. Updating Boolean State
Boolean state stores either true or false. It is useful for showing or hiding content, opening menus, and enabling or disabling interface elements.
import { useState } from "react";
function StudentMessage() {
const [isVisible, setIsVisible] = useState(false);
function toggleMessage() {
setIsVisible(!isVisible);
}
return (
<div>
<h2>Welcome, SAMIKSHA!</h2>
<button onClick={toggleMessage}>
{isVisible ? "Hide Message" : "Show Message"}
</button>
{isVisible && (
<p>Welcome to CIIT Training Institute!</p>
)}
</div>
);
}
export default StudentMessage;
Expected Browser Output
Initially: The welcome message is hidden.
After clicking Show Message: The welcome message appears.
After clicking Hide Message: The message disappears.
6. Direct Value vs Functional Update
React supports two common ways to request a state update: passing a next value or passing an updater function.
| Method | Example | When to Use |
|---|---|---|
| Direct value | setCount(10) |
When the next value is already known. |
| Calculate from current render | setCount(count + 1) |
For a straightforward update based on the current value. |
| Functional update | setCount(previousCount => previousCount + 1) |
When the next value depends on the previous state. |
import { useState } from "react";
function CourseCounter() {
const [count, setCount] = useState(0);
function completeLesson() {
setCount(previousCount => previousCount + 1);
}
return (
<div>
<h2>SAMADHAN's Completed Lessons: {count}</h2>
<button onClick={completeLesson}>
Complete Lesson
</button>
</div>
);
}
export default CourseCounter;
7. State Update Flow Diagram
The following diagram summarizes how a state update changes what the user sees.
8. Common State Updating Mistakes
Mistake 1: Direct assignment
count = count + 1;
This assignment does not request a React state update. Use the setter function.
setCount(count + 1);
Mistake 2: Expecting the value to change immediately
setCount(count + 1); console.log(count); // Value from the current render
The console statement reads the state value belonging to the current render. The setter requests an update for a subsequent render.
Mistake 3: Mutating an object or array
When updating objects and arrays, create a new value instead of directly modifying the existing state. We will study this in the upcoming lessons.
9. Practice Exercises
Practice these examples for the CIIT React tutorial:
- Create a counter that starts at 5 and increases on each click.
- Change the student name from SAMADHAN to SAMIKSHA.
- Display a welcome message for PRADNYA when a button is clicked.
- Change a course status from In Progress to Completed.
- Create a Boolean state to show or hide course details.
- Explain the difference between direct and functional updates.
10. Quick Revision
- State updates are requested through setter functions.
- State can store strings, numbers, Boolean values, objects, and arrays.
- Direct assignment does not request a React state update.
- Functional updates calculate the next value from the previous state.
- React renders the component using its updated state.
- State makes interactive course dashboards and forms possible.
Summary
Updating state is essential for building interactive React applications. A setter function requests a new state value, and React can render the component with that updated value. You can update numbers, strings, and Boolean values, while functional updates are useful when the next value depends on the previous state. In the next lesson, we will learn how functional state updates work in detail.