State

useState remembers a value, and the screen redraws when it changes

Key points

  • Keep values that change in useState: const [count, setCount] = useState(0)
  • To change the value, always use setCount(nextValue)
  • When the value changes, React redraws the screen for you. No need to update the DOM yourself

Try it

import { useState } from "react"

export default function App() {
  const [count, setCount] = useState(0)

  return (
    <div style={{ padding: 16 }}>
      <p>Clicks: {count}</p>
      <button onClick={() => setCount(count + 1)}>+1</button>
    </div>
  )
}
  1. Change +1 to +10
  2. Add a −1 button (hint: setCount(count - 1))
  3. Add a reset button that goes back to 0 (hint: setCount(0))

Common pitfalls

let count = 0 won't update the screen
Changing a regular variable doesn't tell React it needs to redraw the screen. Keep values that change in useState.
onClick={setCount(count + 1)} runs right away
onClick needs "a function to run later". Wrap it in a function, like () => setCount(count + 1).