Events
- React
- JavaScript
How React components respond to user interaction by attaching handler functions to elements, typically updating state in response.
Prerequisites
- State and the setter (see Related Topics)
What you'll understand
- How to respond to user interaction in React
- How to attach an event handler correctly
- How events and state work together to update the UI
Explanation
Events are how your UI responds to the user: a click, a key press, a change in an input. In React you handle them by passing a function, an event handler, to a special prop on an element, such as onClick or onChange. When the user performs the action, React calls your function.
The most important detail is that you pass the function itself, not the result of calling it. onClick={handleClick} hands React the function to call later; onClick={handleClick()} calls it immediately during render, which is a common bug. When you need to pass arguments, wrap the call in an inline arrow function so it runs only on the event.
Events are what make an app interactive, and they almost always work with state (see Related Topics). A handler typically reads the interaction and calls a state setter, which re-renders the component with the new value. The loop, user acts, handler updates state, UI re-renders, is the heart of how a React interface responds.
Examples
An event handler updates state, which re-renders the component:
import { useState } from 'react';
function Toggle() {
const [on, setOn] = useState(false);
return <button onClick={() => setOn(!on)}>{on ? 'On' : 'Off'}</button>;
}Pass the function, not its result; use an arrow function when you need to pass arguments:
<button onClick={handleClick}>OK</button> {/* correct */}
<button onClick={() => remove(id)}>Delete</button> {/* correct, with an argument */}Common mistakes
- Calling the handler during render with onClick={handleClick()} instead of passing it.
- Forgetting to wrap a handler that needs arguments in an arrow function.
- Doing heavy work in a handler when it should just update state.
- Expecting to read the new state value immediately inside the same handler.
Best practices
- Pass the handler function by reference, not its return value.
- Use an inline arrow function only when you need to pass arguments.
- Keep handlers small: read the event and update state.
- Name handlers clearly, often starting with handle.
Further reading
- React, Responding to events — https://react.dev/learn/responding-to-events