- Home
- Javascript
- What is State? Introducing useState
React useState Hook: State Management for Beginners
Contents
What is State? Introducing useStateWhat is State?
Props come from outside and never change. State is data that lives inside a component and can change over time.
Anything that changes in response to the user belongs in state:
- The text typed into a search box
- Whether a menu is open
- The number of items in a cart
- A list of tasks the user has added
Why is it Used?
Try this and watch it fail:
jsx
function Counter() {
let count = 0;
function handleClick() {
count = count + 1;
console.log(count); // The console shows 1, 2, 3...
}
return (
<div>
<p>Lessons completed: {count}</p>
<button onClick={handleClick}>Complete lesson</button>
</div>
);
}The console shows the number increasing, but the screen stays at 0. React does not watch ordinary variables. It has no idea anything changed, so it never re-renders.
State solves exactly this. When state changes, React re-renders the component.
Syntax
jsx
import { useState } from "react";
const [value, setValue] = useState(initialValue);- value — the current value
- setValue — the function that updates it
- initialValue — the starting value
useState is a Hook. Hooks are functions React provides that let components do things like hold state. You will learn the full set in Module 7.
Example
src/components/LessonCounter.jsx
jsx
import { useState } from "react";
function LessonCounter() {
const [count, setCount] = useState(0);
function handleComplete() {
setCount(count + 1);
}
return (
<div>
<h3>React Fundamentals</h3>
<p>Lessons completed: {count}</p>
<button onClick={handleComplete}>Complete lesson</button>
</div>
);
}
export default LessonCounter;How It Works
- import { useState } from "react"; Hooks must be imported. This uses curly braces because useState is a named export.
- const [count, setCount] = useState(0); array destructuring. count starts at 0.
- setCount(count + 1) tells React the value changed.
- React re-runs the component function with the new value, and the screen updates.
The naming convention is [thing, setThing]. Follow it every React developer expects it.
Output
The number next to "Lessons completed" increases by one each time the button is clicked.








