State & useState

Give your components a memory that persists across renders and triggers UI updates.

React4 min readConcept 8 of 46

What it is

**State** is a component's memory. It allows a component to remember data between renders.

In functional components, you add state using the useState hook. It returns an array with exactly two values: the current state value, and a setter function to update it.

Why regular variables don't work

If you try to use a standard local variable (let count = 0) and update it (count++) on a button click, two things go wrong:

1. React doesn't know the variable changed, so it won't re-render the screen to show the new value.

2. Even if React did re-render, the function would run from the top again, resetting let count = 0 back to zero.

useState solves both problems: it persists the data across renders, and calling the setter function tells React to update the screen.

How to use it

You call const [count, setCount] = useState(0);. The 0 is the initial value.

When the user clicks a button, you call setCount(count + 1). This does not change the count variable immediately. Instead, it queues a re-render. React then calls your component function again, this time providing 1 as the new count.

The Memory Test

Compare a standard local variable against a React state variable. Notice how only the state variable manages to update the screen and remember its value.

import { useState } from "react";
 
export default function Counter() {
// ❌ Resets on render, doesn't update UI
let localCount = 0;
// ✅ Persists across renders, updates UI
const [stateCount, setStateCount] = useState(0);
 
return (
Local: {localCount}
State: {stateCount}
);
}

Hint: The local variable actually changes in memory, but because it doesn't trigger a render, the UI is stuck. When the state button triggers a render, the function runs from the top, resetting localCount back to 0.

Click the Local button. Notice nothing happens. Click the State button. Notice the screen updates, and the Local variable resets to 0!

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1Why can't you just use standard local variables (e.g., `let x = 0`) for component data that changes?
  2. 2What does the `useState` hook return?
  3. 3What happens if you directly modify a state variable (e.g., `count = 5`) instead of using the setter function?

Remember this

  • State allows a component to remember data between renders.
  • Calling the setter function triggers a re-render.
  • Never mutate state directly; always use the setter function.
  • State variables are snapshots of the current render, not live reactive proxies.

Done with this concept?

Mark it complete to track your progress. No login needed.