Store component state with useState
Remember a value between renders
State is information a component retains while it remains mounted in the same position. Use the useState Hook when an interaction must change what the interface displays. These independent App.jsx examples assume the approved Chapter 3 React DOM project with automatic JSX transformation. Screen results are predicted, not browser-tested.
import { useState } from 'react';
export default function App() { const [packed, setPacked] = useState(0); return <main><h1>Packing station</h1> <p role="status">Packed: {packed}</p> <button type="button" onClick={() => setPacked(packed + 1)}>Pack one</button> </main>;}The display starts at Packed: 0. Each separate activation adds one. Array destructuring gives the current number and its setter. The setter requests an update; React calls the component again with the new value and commits necessary DOM changes. State is not permanent storage: a fresh mount starts from the initial value. Call useState at the top level of a component, before conditional returns, not within a loop or event handler.
Keep each component instance independent
import { useState } from 'react';
function Station({ name }) { const [ready, setReady] = useState(false); return <section><h2>{name}</h2> <button type="button" aria-pressed={ready} onClick={() => setReady(previous => !previous)}>Ready</button> <p>{ready ? 'Ready to pack' : 'Not ready'}</p> </section>;}
export default function App() { return <main><h1>Stations</h1><Station name="North" /><Station name="South" /></main>;}Both stations begin not ready. Activating North changes only North; its toggle exposes the pressed state to assistive technology. Each mounted Station has its own state. The label Ready stays stable as the toggle changes. The updater receives the previous pending value, so it can calculate its opposite.
Why an ordinary variable is not enough
export default function App() { let packed = 0; return <main><h1>Packing station</h1><p>Packed: {packed}</p> <button type="button" onClick={() => { packed += 1; }}>Pack one</button> </main>;}The click changes a JavaScript variable captured by the handler but does not notify React. The displayed count stays at zero in this isolated example; a new render also creates a fresh local variable. Use the state pair in the first example instead. A variable can still be useful for calculations during a render; it just is not retained React state.
Practice
Build two independent checklist toggles. Start both unchecked or not ready. Activate the second twice and verify that the first never changes. Explain why a shared module variable is not a suitable replacement for component state.