State with useState
State is data that can change while the page is open, like a counter, a cart total or a text box. When state changes, React redraws the component.
Create state with the useState hook. It gives you the current value and a function to change it.
Props come from outside; state belongs to the component itself and remembers things between renders: how many times a button was clicked, whether a menu is open, what's typed in a search box. A normal variable inside a component is reset every time the component runs, so it can't remember anything - that's why state exists.
Each time you call the setter (setCount), React stores the new value and runs your component function again with it. The new JSX is compared with the old, and only the changed parts of the page are updated. This "state changes -> component re-renders" cycle is the heart of how React works.
const [count, setCount] = React.useState(0);<!DOCTYPE html>
<html>
<body>
<div id="root"></div>
<script src="https://unpkg.com/react@18.3.1/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.24.7/babel.min.js"></script>
<script type="text/babel">
function Counter() {
const [count, setCount] = React.useState(0);
return (
<div>
<p>Items in cart: {count}</p>
<button onClick={() => setCount(count + 1)}>Add item</button>
<button onClick={() => setCount(0)}>Empty cart</button>
</div>
);
}
function App() {
return <Counter />;
}
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
</script>
</body>
</html>▶ Try it yourselfsetCount), never by assigning directly (count = 5). Only the setter tells React to update the screen.import { useState } from "react"; and then just useState(0). Here it is React.useState because React is loaded from the internet.- State is data a component remembers and can change.
useState(start)returns[value, setValue].- Calling the setter re-renders the component.
- Never change state directly.
