Skip to content
Parwaz DigitalMarketing · Web · Courses

Web Development Course · Module 5, lesson 3

State and interactivity with useState

Add interactivity to React components with the useState hook, handle events, and build controlled form inputs that update as people type.

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.

Practice task

Add a search box to your React bakery page that filters the product cards as you type, and a button on each card that toggles between "Add to order" and "Added".

Web Development Course

Learn this properly,with a final project.

These pages summarise each lesson. The full course teaches them hands-on. Message us for the current fee, schedule, and format.

Available for new projects — Replies within one business day