React Tutorial

Events and Local State

Respond to user actions and remember component-specific values with useState.

Concept

Event handlers are functions passed to JSX elements. Pass the function itself rather than calling it during render, so React can run it when the event occurs.

The useState Hook gives a component a state value and a setter. Calling the setter requests another render with a new state snapshot; update objects and arrays by creating replacement values instead of mutating existing state.

Example

import { useState } from "react";

export default function Counter() {
    const [count, setCount] = useState(0);
    return <button onClick={() => setCount(count + 1)}>
        Practice count: {count}
    </button>;
}
Type the example yourself and change at least one value. Small experiments reveal syntax and behavior faster than passive reading.

Practice Tasks

  1. Build a button that toggles a help message.
  2. Create a counter with increment and reset actions.
  3. Add an item to state without mutating the existing array.

Key Takeaways

  • Handlers describe responses to interactions.
  • State stores information between renders.
  • State updates should replace rather than mutate data.