React Event Handling Guide

Does your whole web page reload when you click a button? Does your input box fail to update the state while you type? You might face these issues if you do not handle events correctly in React.

Event handling means capturing user actions like clicks, submits, or changes and responding to them. React uses a system called SyntheticEvent. This ensures your code works the same way across all browsers like Chrome, Safari, and Firefox.

Key differences between HTML and React events:

  • Naming: Use camelCase in React. Use onClick instead of onclick.
  • Handlers: Pass a function reference in React. Use curly braces instead of strings.
  • Prevention: Always call event.preventDefault() to stop default browser behavior.

How React handles events:

React does not attach listeners to every single node. It uses Event Delegation. It attaches a single listener to the root element. This saves memory and improves performance.

Common patterns to use:

  • Click Counter: Use a function to update state when a user clicks a button.
  • Form Handling: Use event.target.name and event.target.value to update multiple input fields with one function. Always use event.preventDefault() on form submission to stop page reloads.
  • Passing Arguments: If you need to pass an ID to a function, use an arrow function. Write onClick={() => handleDelete(id)}. Do not write onClick={handleDelete(id)} because it runs immediately during render.

Avoid these mistakes:

  • Infinite Loops: Never call a function directly in an onClick attribute. This triggers a state update during render, which causes another render.
  • Undefined Events: Always include the event parameter in your function definition if you need to call preventDefault().
  • Memory Leaks: If you add manual listeners like window.addEventListener in a useEffect hook, always remove them in the cleanup function.

Best practices for performance:

  • Avoid creating new functions inside a .map() loop if your list is huge.
  • Use the useCallback hook when passing handlers to child components.
  • Clean up custom event listeners to keep your app fast.

Mastering events is the key to building interactive React applications.

Source: https://dev.to/banti_kevat_8e2d123bb7994/react-me-events-handling-complete-guide-2p69