CodeBlanks Logo Icon CodeBlanks

What is state?

Learn that state is data inside a component that can change.

What is state?

A component's state is data that changes over time. A counter, the text in an input, an open menu — all of these are state.

A plain variable does not work: each render resets it. To let React know about changes you use the useState hook.

useState gives you a "box" that remembers and re-renders on change. We will go deeper on this box later.

The useState box

useState returns two things: the current value and a function to update it. We unpack them with destructuring.

Form: const [count, setCount] = useState(0). Here count is the value, setCount the updater, 0 the initial value.

The initial value is used on the first render; later renders give back the remembered value.

Practice Counter skeleton

Complete the skeleton. Write a Counter component; import useState. Define const [count, setCount] = useState(0); and return <p>{count}</p>. Export it.

Starter code

App.jsx
import { useState } from "react";

// Define Counter here

Sample solution

App.jsx
import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);
  return <p>{count}</p>;
}

export default Counter;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why is a plain let variable not enough for state?

App.jsx
useState keeps the value across renders.
  • The syntax is wrong
  • It is slow
  • Each render resets it Correct answer
  • It throws a type error

Explanation: A local variable restarts on each render; React does not see the change.

2 What is state: fill in the missing part

Question
const [count, ____] = useState(0);
Answer
const [count, setCount] = useState(0);

Explanation: The updater is taken as setCount.

3 What is state: match the terms

Term Meaning
count Current value
setCount Updater
useState Hook
0 Initial value

All lessons in Beginner