What Is State?
So you've learned about props โ they're how data flows down from parent to child. But what happens when you need your component to remember something? That's where state comes in. State is a component's memory. It's the data that changes over time as the user interacts with your app.
Think of props as the input to a function, and state as the variables inside that function. Props come from outside; state lives inside. When state changes, the component re-renders โ that's React's way of updating the screen to show the latest data.
The useState Hook
The useState hook is how you create and manage state in a functional component. It gives you a piece of state and a function to update that piece. You call it at the top of your component, and React handles the rest.
Every time you call the setter function, React remembers the new value and re-renders your component with it. It's like your component has a little notebook that it keeps updating.
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Try it Yourself โ
State Updates Trigger Re-renders
Here's the magic: when state changes, React automatically re-renders your component. You don't need to manually update the DOM. React figures out what changed and updates only that part of the screen. It's efficient and saves you from a lot of headaches.
But remember โ state is immutable. Never modify state directly. Always use the setter function to update it. If you try to do count = count + 1, React won't know about it and nothing will update on screen.
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
function handleReset() {
setCount(0);
}
Try it Yourself โ