React / 22
Why a plain variable won't update the screen
Changing a normal variable doesn't re-render anything. State is data React keeps between renders, and changing it tells React to draw again.
Try it
A variable vs state
Try itlet count = 0renders: 10
console.log(count) → nothing yet
useState(0)renders: 10
each click: new value → new render
Why the variable doesn't work
export default function Counter() {
let count = 0;
function handleClick() {
count = count + 1;
console.log(count); // 1, 2, 3… it really changes
}
return <button onClick={handleClick}>Clicked {count} times</button>; // always 0
}Two separate problems:
- React doesn't watch your variables. Changing
countis invisible to React, so it never re-runsCounter, and the JSX on screen still says 0. - Even if it re-rendered, the variable would reset. A render means calling
Counter()again, from the top.let count = 0runs again, and the old value is gone.
So you need two things: a value that survives between renders, and a way to tell React it changed. That's state.
The fix: useState
import { useState } from "react";
export default function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>Clicked {count} times</button>
);
}useState(0) gives you the current value and a setter. Calling setCount stores the new value inside React and asks React to render Counter again. On that render, useState hands back the new value, and the JSX shows it.
UI is a function of state
This is the core idea of React: UI = f(state). You don't change the screen. You change the data, and React re-runs your component to get the new screen. Your app has a data layer (state) and a UI layer (JSX), and React keeps the second in sync with the first.
So what's a hook?
useState is a hook: a function whose name starts with use that lets a component use a React feature. useState gives memory, useEffect runs code after rendering, useContext reads shared data, and so on.
Hooks are plain JavaScript functions, but they only work while React is rendering a component, because they read and write that component's slot inside React. That's why they come with rules, covered later in this chapter.
Gotchas
Recall
Can you answer these?
0/4
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
