React · 3 minute lesson
State stores information that a React component needs to remember between renders. Changing an ordinary local variable does not tell React to update the screen. The useState Hook supplies a current value and a setter that requests a new render.
Call Hooks at the top level of a component, before conditional returns. Attach an event handler by passing a function to the event prop. For example, onClick receives a function; calling the function while rendering would run it immediately instead of waiting for the click.
When the next value depends on the previous value, a functional update communicates that relationship clearly. Keep each state value focused on information that can actually change. Values that can be calculated from existing state can usually be calculated during rendering, which avoids having two copies that could disagree.
Try the example
import { useState } from "react";
export default function LessonCounter() {
const [completed, setCompleted] = useState(0);
return (
<button onClick={() => setCompleted(value => value + 1)}>
Completed: {completed}
</button>
);
}Practice
Add a reset button that sets the count to zero. Then add a message when the learner reaches three completed lessons. Refresh the page and observe that local component state is initialized again.
Continue learning: Official documentation.