AI Hints
Home›React Tutorial›Events and State
React · Lesson 20 of 120

State

UseState.

⏱ 2 min read▶ Video at 15:15🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

Clicking does nothing visible yet, because a normal variable doesn't update the page. Components need state, data that React remembers between renders. Changing it makes React render again.

  • Variables don't update the page
  • State does
  • React renders again

A counter

Use state gives us the current value, starting at zero, and a setter function. Clicking calls the setter with the count plus one. React renders again with the new count. We click three times. Run it.

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

export default function App() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p className="big">{count}</p>
      <button id="plus" onClick={() => setCount(count + 1)}>Add a helmet</button>
    </div>
  );
}
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}
Also uses actions.json
[{"click": "#plus", "times": 3}]

useState in short

Call use state at the top of your component, with a starting value. It returns a pair. The current value, and a function to set a new one. Never change state directly, always use the setter.

keyvalue
CalluseState(initial)
Returns[value, setValue]
ChangesetValue(new)
Nevervalue = new

Summary

Use state remembers data, and its setter tells React to render again. Next, how state updates work.

Key takeaways
  • useState(0)
  • [count, setCount]
  • Re-render
Next up: How State Updates — a new render