Props and state

Add state with useState

Remember a value between renders and request a new render through its setter.

State lets a component remember information between renders.

import { useState } from 'react'

function Counter() {
  const [count, setCount] = useState(0)

  return (
    <button onClick={() => setCount(count + 1)}>
      Count: {count}
    </button>
  )
}

useState(0) gives this component position an initial value. During a render, count is that render’s snapshot. Calling setCount() requests another render with a new value.

The setter does not change the existing count variable. React calls the component again and gives the next render its own value.

Use state when information changes over time and affects the rendered result. Keep derived values as calculations:

const completed = tasks.filter(task => task.done).length

Storing completed separately would create two values that can disagree.

State belongs to a component position. Rendering two counters creates two independent state values even though both call the same component function.

Click one of two counters and confirm only that instance changes. Then log count immediately after setCount() and explain why it still contains the current render’s value.

Lesson completed

Take this course offline

Get every free book, course edition, and software download.

Get the download library →