State, events, and forms

19.3

State holds values that affect the component’s output. Set state from event handlers to update the UI.

On this page

Update from previous state

Call Hooks at the top level of a component or custom Hook. When the next value depends on the previous value, pass an updater function. For objects and arrays, build a new value and pass it to the setter.

import { useState } from "react";

export default function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(value => value + 1)}>{count}</button>;
}

Keep an input in sync

A controlled text input gets its value from state and updates it in onChange. Start with an empty string if there is no value. In a form handler, call preventDefault when you intend to handle submission in JavaScript.

import { useState } from "react";

export default function SearchBox() {
  const [query, setQuery] = useState("");

  return (
    <form onSubmit={event => event.preventDefault()}>
      <label>
        Find a product
        <input value={query} onChange={event => setQuery(event.target.value)} />
      </label>
      <p>Search term: {query}</p>
    </form>
  );
}

Official references