Zum Hauptinhalt springen

Turn a local variable into real state

Replace a non-persistent local variable with `useState` to retain data and trigger renders.

react-basics5 min read

A Gallery component declares let index = 0. handleNext runs index = index + 1, but the displayed item never changes. State gives React memory and a render trigger Changing a local variable inside an event handler does not persist across renders and does not ask React to render again. Locate the changing value The selected gallery item is controlled by index. A value that changes after a user click and affects rendering needs component memory. Replace the local variable Use const [index, setIndex] = useState(0) at the top level of the component. useState returns the current value and a…

Read the full lesson

Sign up free: one personalized lesson every day, matched to your role and goals.

← Back to library

Kontakt aufnehmen