State — Component's Short-term Memory
Regular functions in JavaScript are " one-time " : they execute and forget everything. But React components are functions that are called hundreds of times per minute (every time on update). For a component to be able to " remember " something between these calls, we need State.
1. Problem: Why Don't Regular Variables Work?
You can create a variable let count = 0, but on every click it will reset to 0 because React calls the entire component function again.
Also, React is " lazy. " If you just change a variable, it won't understand that it needs to redraw the screen. It needs an official notification.
2. Analogy: Frames in a Film (Snapshots)
This is the most important and complex concept to understand. When React calls your component, it makes a Snapshot of how the interface should look right now, based on current data.
Imagine your state is a frame number in a movie.
- When you call
setScore(score + 1), you're not changing the digit in the current frame. - You're telling React: " Hey, in the next frame add one! " .
- Therefore, if you write
console.log(score)right aftersetScore, you'll see the old value. You're still in the current frame where the digit hasn't changed yet.
3. Anatomy of useState
const [status, setStatus] = useState('offline');
This is called array destructuring.
- status (Value): What we show on screen right now.
- setStatus (Dispatcher): A function that does two things:
- Saves the new value in React's memory.
- Shouts: " Time to redraw! " (triggers render).
- 'offline': Initial value, used only once — when the component first appears.
4. How It Updates (Lifecycle)
- Trigger (Event): User pressed a button.
- Dispatch (Call): We call
setStatus('online'). - Render (Calculation): React calls your component function again. This time
statusequals 'online'. - Commit (Print): React compares changes and updates only the needed piece of text in the real browser.
Understanding state as a 'snapshot', you'll stop being surprised by 'strange' variable behavior and start writing predictable code.