Introduction to State in React
State is a fundamental React concept that allows components to remember information, respond to user interactions, and display updated data. In this lesson, we will understand state through diagrams, examples, and practical applications.
1. What Is State in React?
State is data that a React component manages over time. Its value may change when a user clicks a button, enters information, selects an option, or performs another action.
When state is updated through its setter function, React schedules a render so that the component can display the latest state value.
- State stores changing information.
- State belongs to a component instance.
- State updates can cause the UI to render again.
- State is useful for forms, counters, menus and dashboards.
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
}
export default Counter;
Expected Browser Output
Initially: Count: 0
After one click: Count: 1
After two clicks: Count: 2
2. Why Do We Need State?
Normal JavaScript variables alone do not tell React that the UI needs to be updated. State gives React a way to preserve a value between renders and respond to changes.
| Application | Example State |
|---|---|
| Counter | Current count |
| Student registration | Name and form field values |
| Navigation menu | Whether the menu is open |
| Course dashboard | Selected course or filter |
| Shopping cart | Selected cart items |
3. State Update Flow Diagram
This diagram explains how a user action updates state and how React displays the new value.
Step-by-step explanation:
- The user clicks the Increase button.
- The onClick event handler executes.
- The setter requests a state update.
- React renders the component with the updated state.
- The displayed count changes from 0 to 1.
4. Understanding the useState Hook
The useState Hook allows a functional component to declare state. It provides the current state value and a function used to request updates to that value.
const [count, setCount] = useState(0);
| Part | Explanation |
|---|---|
| useState | The React Hook used to declare state. |
| count | The current state value for this render. |
| setCount | The function used to request a state update. |
| 0 | The initial state value for the first render. |
5. Practical Example: Course Status
Imagine a CIIT student dashboard. A course initially shows In Progress. When the student clicks Complete Course, the status changes to Completed.
import { useState } from "react";
function CourseStatus() {
const [status, setStatus] = useState("In Progress");
function completeCourse() {
setStatus("Completed");
}
return (
<div>
<h2>React Fundamentals</h2>
<p>Status: {status}</p>
<button onClick={completeCourse}>
Complete Course
</button>
</div>
);
}
export default CourseStatus;
Expected Browser Output
Course: React Fundamentals
Initial Status: In Progress
After clicking the button: Completed
Here, status stores the current value and setStatus requests the update. React then renders the component with the new status.
6. State vs Normal Variables
A normal local variable does not itself trigger a React render. React state is preserved between renders, and updating state through its setter can schedule a new render.
| Normal Variable | React State |
|---|---|
| Does not itself trigger a React render. | Setter updates can schedule a render. |
| Local value is recreated when the function runs again. | React preserves state between renders. |
| Useful for temporary calculations. | Useful for values that affect the UI. |
7. Important Rules of State
- Use a state setter to update state.
- Do not mutate state objects or arrays directly.
- Call Hooks at the top level of functional components.
- React may batch state updates.
- Use a functional update when the next value depends on the previous value.
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
function increase() {
setCount(previousCount => previousCount + 1);
}
return (
<button onClick={increase}>
Count: {count} - Increase
</button>
);
}
export default Counter;
Expected Browser Output
Initially: Count: 0
After clicking: Count: 1
8. Common Mistakes
- Assigning a new value directly to a state variable.
- Forgetting to import useState.
- Calling a Hook inside an if statement or loop.
- Expecting the current state variable to change immediately in the same handler.
- Using state for a value that can simply be calculated during rendering.
// Incorrect count = count + 1; // Correct setCount(count + 1); // When based on the previous value setCount(previousCount => previousCount + 1);
9. Quick Practice
Try these exercises in your React project:
- Create a counter with Increase and Decrease buttons.
- Create a toggle button to show or hide a message.
- Build a student form with a state variable for the name.
- Change a course status from Learning to Completed.
- Explain how the state setter causes the UI to update.
10. Quick Revision
- State stores changing information in a component.
- useState is a Hook for declaring state.
- The setter requests a state update.
- React renders the component using the latest state.
- State is essential for interactive React applications.
Summary
State is a core React concept that lets components preserve changing data between renders. The useState Hook provides the current value and a setter function. When the setter requests an update, React can render the component with the latest value and update the UI. State is useful for counters, forms, menus, course progress and other interactive features. Understanding state prepares you for the next lessons on useState, updating state, functional updates, objects, arrays, immutability and lifting state up.