What is State
In React, state is a built-in object that allows components to store and manage data that can change over time. It helps React know when to re-render a component when something has changed.
🔹 What is State?
State is:
- A JavaScript object used to store dynamic information.
- Private and controlled by the component (unlike props which are passed in from the parent).
- Triggers a re-render when it updates.
🧱 Basic Example:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // count is the state variable
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
count
is the state value.setCount
is the function to update the state.useState(0)
initializescount
to0
.
⚙️ Common Features of State:
Feature | Description |
---|---|
Initial state | Set using useState(initialValue) |
Update state | Call the update function (e.g., setCount ) |
Triggers re-render | React automatically updates the UI |
Local to component | Each component manages its own state |
🧠 Multiple State Variables:
const [name, setName] = useState("Jigang");
const [age, setAge] = useState(30);
You can have multiple independent state variables inside a single component.
🔄 Updating State (Important!)
- Don’t mutate state directly:
❌count++
✅setCount(count + 1)
- React may batch updates, so don’t rely on the current state when updating multiple times in a row. Use a function form when needed:
setCount(prev => prev + 1);
🧠 Summary:
Term | Meaning |
---|---|
useState | React Hook to add state to a function component |
State | Data that changes over time |
setState | Function to update state and re-render component |
Comments are closed.