Skip to content
ClapelloNotes by Barath
ReactCh 05 · 1/6
Beginner3 min readUpdated

React / 22

Why a plain variable won't update the screen

TL;DR

Changing a normal variable doesn't re-render anything. State is data React keeps between renders, and changing it tells React to draw again.

Try it

A variable vs state

Try it
let count = 0renders: 1

0

console.log(count) → nothing yet

useState(0)renders: 1

0

each click: new value → new render

Click both buttons a few times. The variable really changes (see the console line), but the screen and the render count never move. State re-renders every time.

Why the variable doesn't work

Counter.jsx
export default function Counter() {
  let count = 0;
 
  function handleClick() {
    count = count + 1;
    console.log(count); // 1, 2, 3… it really changes
  }
 
  return <button onClick={handleClick}>Clicked {count} times</button>; // always 0
}

Two separate problems:

  1. React doesn't watch your variables. Changing count is invisible to React, so it never re-runs Counter, and the JSX on screen still says 0.
  2. Even if it re-rendered, the variable would reset. A render means calling Counter() again, from the top. let count = 0 runs again, and the old value is gone.

So you need two things: a value that survives between renders, and a way to tell React it changed. That's state.

The fix: useState

Counter.jsx
import { useState } from "react";
 
export default function Counter() {
  const [count, setCount] = useState(0);
 
  return (
    <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>
  );
}

useState(0) gives you the current value and a setter. Calling setCount stores the new value inside React and asks React to render Counter again. On that render, useState hands back the new value, and the JSX shows it.

UI is a function of state

This is the core idea of React: UI = f(state). You don't change the screen. You change the data, and React re-runs your component to get the new screen. Your app has a data layer (state) and a UI layer (JSX), and React keeps the second in sync with the first.

So what's a hook?

useState is a hook: a function whose name starts with use that lets a component use a React feature. useState gives memory, useEffect runs code after rendering, useContext reads shared data, and so on.

Hooks are plain JavaScript functions, but they only work while React is rendering a component, because they read and write that component's slot inside React. That's why they come with rules, covered later in this chapter.

Gotchas

Recall

Can you answer these?

0/4

Answer out loud (or in your head) before you tap. That's what makes it stick.

Saved on this device only. No login.