State is an internal data store for a component. Unlike Props (which are fixed), State is meant to change over time based on user interaction.
When the state changes, React "re-renders" the component to show the updated data on the screen automatically.
Think of it as a continuous loop. The user acts, the data changes, and the view follows the data.
Rule 1: Private - State belongs only to the component it is defined in.
Rule 2: useState Hook - We use the useState hook to create state.
Rule 3: Never Mutate Directly - Always use the "Setter" function.
// ❌ WRONG count = count + 1; // ✅ CORRECT setCount(count + 1);
Rule 4: Trigger - Updating state is the only way to tell React to refresh the screen.
import { useState } from "react";
const [count, setCount] = useState(0);
| Part | Meaning |
|---|---|
| count | The Variable holding the current value |
| setCount | The Function used to change the value |
| useState(0) | Starting value (Initial State) |
import { useState } from "react";
function App() {
const [count, setCount] = useState(0);
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
}
export default App;
| Feature | Props | State |
|---|---|---|
| Source | From Parent | Internal |
| Editable | No (Read-only) | Yes |
| Purpose | Configuration | Interactivity |
Standard JS variables (let x = 0) do not trigger a UI refresh. Only State triggers a re-render.
A "Like" button is a perfect state example. The number of likes is the state.
Advanced: Create a "Show/Hide" button that displays a secret message only when clicked.
JSX → Props → State (Complete)
↓
Next: Events → Hooks → API Integration