Events

Handle user actions with onClick and onChange

Key points

  • Handle clicks with onClick and typing with onChange. Unlike HTML's onclick, the second word is capitalized
  • Pass "a function to run later". Write onClick={handleClick} without ()
  • To call it with arguments, wrap it in () =>: onClick={() => setCount(0)}

Try it

import { useState } from "react"

export default function App() {
  const [message, setMessage] = useState("Not clicked yet")

  function handleClick() {
    setMessage("Clicked!")
  }

  return (
    <div style={{ padding: 16 }}>
      <button onClick={handleClick}>Click me</button>
      <p>{message}</p>
    </div>
  )
}
  1. Add an "Undo" button that resets the message to the original
  2. Change onClick to onMouseEnter so it reacts when you just hover over it
  3. Try adding () like onClick={handleClick()} and see what happens

Common pitfalls

onClick={handleClick()} runs the moment it's displayed
Adding () passes "the result of running it right now". Pass the function itself: onClick={handleClick}.
Name event functions handle + action
Names like handleClick, handleSubmit, and handleReset make it clear at a glance what the function does. It's the standard in real projects too.