Kodokon kodokon.com

Local state with useState

Give your components memory with useState so you can display values that change as the user interacts.

8 min · 3 questions

Open this lesson in Kodokon

A like counter, the text typed into a search field, a menu that opens and closes: all of these values change while the app is being used. A regular variable isn't enough, because React doesn't refresh the screen when it changes. You need what is called state: memory that belongs to the component. You create it with useState, a hook, meaning a special function provided by React whose name starts with use.

JSX
import { useState } from "react";

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

  return (
    <button onClick={() => setCount(count + 1)}>
      Count: {count}
    </button>
  );
}
A counter that increases with every click

Let's break down the key line: const [count, setCount] = useState(0);. useState(0) creates a piece of state with the initial value 0 and returns an array of two elements, which you grab through destructuring: count is the current value, and setCount is the update function, the only allowed way to change that value. Here, onClick triggers setCount(count + 1) on every click (we'll cover events in detail in the next lesson).

JSX
import { useState } from "react";

function NameInput() {
  const [name, setName] = useState("");

  return (
    <div>
      <input
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <p>Hello, {name}!</p>
    </div>
  );
}
State remembers the text typed into the field

When you call setName, React does two things: it stores the new value, then it re-runs your component function to recompute the output. This is called a re-render. That is why the Hello, {name}! paragraph updates on its own with every letter typed: you describe the result, React handles the rest.

Knowledge check

Make sure you remember the key points of this lesson.

  1. What does the call useState(0) return?
    • Only the current value of the state
    • An array with the current value and its update function
    • An object containing all of the component's state
  2. Which is the correct way to increase the counter?
    • count = count + 1
    • useState(count + 1)
    • setCount(count + 1)
  3. What happens when you call a state's update function?
    • React re-runs the component to refresh the display
    • The whole page is reloaded in the browser
    • Nothing, you also have to refresh the page manually