01 / 05

How do we handle events in react.

Difficulty: 4/10
synthetic events, event binding, performance

Handling events with React elements is very similar to handling events on DOM elements.

There are some syntax differences:
  1. 1

    React events are named using camelCase, rather than lowercase.

  2. 2

    With JSX you pass a function as the event handler, rather than a string.

  3. 3

    Another difference is that you cannot return false to prevent default behavior in React. You must call preventDefault explicitly.

Scenario Questions

0-2 years experience

  1. 1You need to add a click handler to a button that toggles a piece of state. Walk me through the JSX and the function you'd write.
  2. 2If you write onClick={handleClick()} instead of onClick={handleClick}, what will happen when the component renders?

2-5 years experience

  1. 1We have a form with multiple inputs and a single submit button. How would you manage the change events to keep the form state in sync, and what pitfalls might you encounter?
  2. 2During a code review you notice a parent passes an inline arrow function as an onClick prop to a frequently re‑rendered child. Explain why this could be a problem and how you'd fix it.
  3. 3A bug appears where clicking a button inside a modal doesn't trigger the handler, but clicking elsewhere works. How would you debug this in React?

5-8 years experience

  1. 1Our list component renders thousands of items, each with its own click handler. Discuss strategies to keep event handling performant and avoid unnecessary re‑renders.
  2. 2We need a custom drag‑and‑drop interaction without a library. Describe how you'd use React's event system to track mouse movements and ensure proper cleanup.
  3. 3Explain the implications of React's event pooling on asynchronous handlers and how you'd adapt your code for a data‑fetching operation triggered by a click.

8+ years experience

  1. 1Our legacy code mixes class and functional components. We're standardizing event handling across the app. What architectural guidelines would you set for consistency, testability, and migration?
  2. 2We want a global event bus to coordinate actions between unrelated components without prop drilling. How would you design this in React, considering the synthetic event system and performance?
  3. 3During a migration to React 18 concurrent mode, what changes, if any, do you anticipate needing to make to existing event handlers to avoid subtle bugs?

Follow-up Questions

  • What happens if you forget to bind a class method used as an event handler?
  • Can you explain how React's event pooling affects async code inside a handler?
  • Why might you choose a memoized callback over an inline arrow function for an onClick prop?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.