Give your components memory with useState so you can display values that change as the user interacts.
Open this lesson in KodokonA like counter, the text typed into a search field, a menu that opens and closes: all of these values change while the app is being used. A regular variable isn't enough, because React doesn't refresh the screen when it changes. You need what is called state: memory that belongs to the component. You create it with useState, a hook, meaning a special function provided by React whose name starts with use.
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}Let's break down the key line: const [count, setCount] = useState(0);. useState(0) creates a piece of state with the initial value 0 and returns an array of two elements, which you grab through destructuring: count is the current value, and setCount is the update function, the only allowed way to change that value. Here, onClick triggers setCount(count + 1) on every click (we'll cover events in detail in the next lesson).
import { useState } from "react";
function NameInput() {
const [name, setName] = useState("");
return (
<div>
<input
value={name}
onChange={(e) => setName(e.target.value)}
/>
<p>Hello, {name}!</p>
</div>
);
}When you call setName, React does two things: it stores the new value, then it re-runs your component function to recompute the output. This is called a re-render. That is why the Hello, {name}! paragraph updates on its own with every letter typed: you describe the result, React handles the rest.
useState(0) return?