What you will learn
- Store and update component state with useState
- Handle click and change events in JSX
- Build a controlled input that filters a list as the user types
Props come from outside a component, while state is data the component manages itself and that can change over time. The useState hook creates it: const [count, setCount] = useState(0). count holds the current value and setCount updates it. When you call the setter, React re-renders the component with the new value, so the screen always matches the data.
Events are attached in JSX with camelCase props, such as onClick and onChange. <button onClick={() => setCount(count + 1)}>Add</button> increases the count on each click. Never change state directly, for example by pushing to an array held in state. Instead, pass a new value to the setter, such as a new array created with the spread syntax or filter.
A controlled input keeps its value in state: <input value={query} onChange={(e) => setQuery(e.target.value)} />. Each keystroke updates query, and you can use it elsewhere, for example products.filter((p) => p.name.toLowerCase().includes(query.toLowerCase())) to show matching items. Hooks must be called at the top level of a component, not inside conditions or loops.


