Lesson 6
22 min
Store data that changes, update the display and follow the rules of hooks.
Definition
A component's state is itsmemory: the collection of data that can change while the user interacts with the interface. Whenever the state changes, Reactre-renders the component with the new values. In React, state is created using thehookuseState.
Until now, your components always displayed the same content: they were static. With state, they become interactive: a counter that increases, a menu that opens, or a form that gets filled in. This is one of the most important concepts in React, and it is worth taking the time to understand it thoroughly. In this lesson, you will learn how to create state, how to update it correctly, and especially why React enforces certain rules that may seem surprising at first.
Lesson Objectives
useState.Props come from outside a component and are not modified by that component. However, some data changes during use: a counter, text entered into an input field, or a menu that is open or closed. We store this information in the component's state. When state changes, Reactautomatically re-renders the component with the new value.
You might wonder why we cannot simply use an ordinary variable. There are two reasons. First, an ordinary variable is initialized again each time the component runs, so it does not preserve its value between renders. Second, even if you change it, React does not know that it needs to update the page. State solves both problems: it is preserved between renders, and updating it tells React that a new render is needed.
The best way to understand this is to look at a failed first attempt. This component tries to count clicks using an ordinary variable. It seems reasonable, but it does not work.
function BrokenCounter() {
let count = 0;
function increment() {
count = count + 1;
console.log("count is", count);
}
return (
<div>
<p>You clicked {count} times.</p>
<button onClick={increment}>Click</button>
</div>
);
}If you click the button, the console correctly displays an increasing number, but the text on the screen remains "You clicked 0 times." Two things happen: the variable changes, but React is not notified, so nothing new appears on the screen. Even if the component re-rendered for another reason, the linelet count = 0would run again and reset the counter to zero. We therefore need a place where React preserves the value and a way to notify it when that value changes. That is exactly what state provides.

The state cycle: action, update, re-render, and another action.
A hook is a special React function whose name begins withuse. The most commonly used hook isuseState. It returns two elements: the current value and afunction to update it.
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times.</p>
<button onClick={() => setCount(count + 1)}>
Click
</button>
</div>
);
}
export default Counter;useState(0): creates state with an initial value of 0.count: the current state value.setCount: the function that updates the state and triggers a new render.Let's walk through what happens. During the first render, React runs the component, anduseState(0)returns the value0. When you click the button, thesetCountfunction is called with the value1. React remembers this new value and runs the component again. This time,useStatereturns1, and the page displays "You clicked 1 times." The cycle repeats with every click.
The initial value is only used once, during the very first render. On subsequent renders, React ignores the argument passed touseStateand returns the value it has stored. That is why the counter does not return to zero when the component re-renders.
The syntax with square brackets is called array destructuring. It lets you assign names to the two returned elements. By convention, the setter function is named using the prefixsetfollowed by the state name, such ascountandsetCount.
// What destructuring does, in two steps
const result = useState(0);
const count = result[0]; // the current value
const setCount = result[1]; // the setter function
// The usual, shorter version
const [count, setCount] = useState(0);You can choose any names: you could write[a, b]and it would still work. However, following the value / set + value convention makes each variable's purpose immediately clear to anyone reading the code. It also keeps your code readable when a component contains several state variables.

Warning
Never modify state directly (for example,count = 5). Since state is declared usingconst, JavaScript will even throw an error. If you declared it withlet, React would not notice the change, and the interface would not update. Always use the setter function provided byuseState.
State is not limited to numbers. It can contain any JavaScript value. The initial value should simply match the type of data you expect the state to hold later. If you expect text, start with an empty string. If you expect a list, start with an empty array.
const [count, setCount] = useState(0); // number
const [name, setName] = useState(""); // text
const [menuOpen, setMenuOpen] = useState(false); // boolean
const [fruits, setFruits] = useState([]); // array
const [profile, setProfile] = useState({ name: "", age: 0 }); // objectHere is something that surprises almost everyone. When you call the setter function, the state variable does not immediately change in the currently running code. It contains the value from the current render, like a snapshot, and will only be updated in thenext render.
function Test() {
const [count, setCount] = useState(0);
function increment() {
setCount(count + 1);
console.log(count); // still displays the previous value
}
return <button onClick={increment}>Value: {count}</button>;
}On the first click, the console displays0, while the button subsequently displays1. This is not a bug: in that particular render, thecountconstant is 0, and it cannot change. The next render runs theTestfunction again with a new constant whose value is 1.
When the new value depends on the previous one, pass afunction to the setter that receives the previous state value. This is safer, especially when several updates happen in succession:
setCount((previous) => previous + 1);Why is this safer? Because React can batch several updates together. If you writesetCount(count + 1)twice in a row, both calls use the same starting value, so the counter only increases by one. With the functional form, each update receives the latest pending value, and the counter increases by two. Get into the habit of using this form whenever the new state depends on the previous state.
function Double() {
const [count, setCount] = useState(0);
function addTwoWrong() {
setCount(count + 1);
setCount(count + 1);
// result: only +1
}
function addTwoCorrect() {
setCount((previous) => previous + 1);
setCount((previous) => previous + 1);
// result: +2
}
return (
<div>
<p>{count}</p>
<button onClick={addTwoWrong}>+2 (wrong)</button>
<button onClick={addTwoCorrect}>+2 (correct)</button>
</div>
);
}In the first function, both calls read the samecountconstant (the snapshot of the current render), so they both request the same final value. In the second function, React processes the updater functions in sequence: the first changes 0 to 1, and the second changes 1 to 2.
You can calluseStateas many times as needed, with one state variable for each piece of information. For an object or array, do not modify it directly. Create a copy using the spread operator.
const [user, setUser] = useState({ name: "Aina", age: 20 });
const [fruits, setFruits] = useState(["apple", "banana"]);
// Object: copy it, then replace one property
setUser({ ...user, age: 21 });
// Array: create a new array with the additional item
setFruits([...fruits, "mango"]);React compares the previous and new state values to determine whether it needs to re-render the component. If you modify an array or object "in place," its reference stays the same, and React does not detect a change. By creating a copy with..., you provide a new value, which triggers a new render. To remove an item from an array, you can also create a new array usingfilter.
For an array stored in state, you need to know how to add, remove, and update an item. Each operation produces anew array instead of modifying the previous one.
const [tasks, setTasks] = useState([
{ id: 1, text: "Review React", done: false },
{ id: 2, text: "Complete the exercises", done: false },
]);
// Add: copy the existing items, then append the new one
function add(text) {
setTasks([...tasks, { id: Date.now(), text: text, done: false }]);
}
// Remove: filter keeps every item except the selected one
function remove(id) {
setTasks(tasks.filter((task) => task.id !== id));
}
// Update: map returns a new array with one item replaced
function toggle(id) {
setTasks(
tasks.map((task) =>
task.id === id ? { ...task, done: !task.done } : task
)
);
}push, create a new array using[...previous, newItem].splice, usefilter.mapand replace the selected item with an updated copy.In the update example, notice the two copies: a new array is created usingmap, and a new object is also created for the selected item using the spread operator. If you simply wrotetask.done = true, you would modify the existing object directly, and React might not detect the change.
With an object, the spread operator copies all existing properties. You then write the properties you want to replace. The order matters: the last value written takes precedence.
const [profile, setProfile] = useState({
firstName: "Aina",
city: "Antananarivo",
age: 20,
});
function changeCity(newCity) {
setProfile({
...profile, // keep firstName and age
city: newCity, // replace only the city
});
}If you forgot...profileand wrote only{ city: newCity }, the new state would contain only the city: the first name and age would disappear. Unlike some older React APIs, the state setter replaces the state rather than merging it.
State is also used to track what the user types. We connect the input's value to state, and each time the user types, we update the state with the entered text. This is called a "controlled" input: React, rather than the browser alone, manages the field's value.
import { useState } from "react";
function Greeting() {
const [name, setName] = useState("");
return (
<div>
<label htmlFor="name">Your name:</label>
<input
id="name"
type="text"
value={name}
onChange={(event) => setName(event.target.value)}
/>
<p>Hello {name === "" ? "stranger" : name}!</p>
</div>
);
}
export default Greeting;With every keystroke, theonChangeevent calls the setter with the input's current text, read fromevent.target.value. The state changes, React re-renders the component, and the paragraph updates in real time. Choosing an initial value of an empty string ("") is important. If you usedundefined, the field would switch from uncontrolled to controlled, and React would display a warning.
Boolean state is perfect for anything that can be "open or closed," "visible or hidden," or "active or inactive." To reverse its value, use the!(NOT) operator, which changestruetofalseand vice versa.
function Menu() {
const [open, setOpen] = useState(false);
return (
<div>
<button onClick={() => setOpen(!open)}>
{open ? "Close menu" : "Open menu"}
</button>
{open && (
<ul>
<li>Home</li>
<li>Courses</li>
<li>Contact</li>
</ul>
)}
</div>
);
}The button reverses the state with each click. Depending on the value ofopen, the button displays different text, and the list is either displayed or hidden. Expressions using?and&&are conditions that we will explain in a dedicated lesson. For now, remember that the interface depends on state.
A common design mistake is creating state for a value that can be derived from other state. Every additional state variable is another value to keep synchronized, which creates more opportunities for mistakes. If information can be calculated from existing state, simply calculate it inside the component.
function Cart() {
const [price, setPrice] = useState(2000);
const [quantity, setQuantity] = useState(3);
// No need for a third state: calculate the total on every render
const total = price * quantity;
return (
<div>
<p>Total: {total} Ar</p>
<button onClick={() => setQuantity(quantity + 1)}>
Add an item
</button>
</div>
);
}Here,totalis a simple constant recalculated on every render. If you stored it in state, you would have to remember to update it whenever the price or quantity changes. Forgetting even once could display an incorrect total.
React identifies each hook by the order in which it is called. If a hook is placed inside a condition, that order may change between renders, and React can no longer determine which state belongs to which hook. That is why these rules are strict: they ensure that hooks are always called in the same order.
// Incorrect: the hook is inside a condition
function Bad({ show }) {
if (show) {
const [text, setText] = useState("");
}
return <p>...</p>;
}
// Correct: the hook is at the top, the condition comes afterward
function Good({ show }) {
const [text, setText] = useState("");
if (!show) {
return null;
}
return <p>{text}</p>;
}In the correct version, the hook is called on every render, in the same order, regardless of the value ofshow. Only the returned result changes. One tip: your editor and development tools will usually warn you when these rules are violated, so read their messages carefully.
count = 5does not trigger a new render.pushon a state array is not the correct approach. Create a new array instead.import { useState } from "react", the hook is not defined.onClick={() => setCount(1)}.State belongs to a component instance, not to the component definition in general. If you display the same component twice, each instance has independent state: clicking one does not change the other. This is what allows you to reuse a component as many times as you want.
import Counter from "./Counter";
function App() {
return (
<div>
<h2>Counter A</h2>
<Counter />
<h2>Counter B</h2>
<Counter />
</div>
);
}
export default App;When you click the first button three times, Counter A displays 3, while Counter B remains at 0. React remembers separate state for each position where the component appears on the page. If a component is removed from the screen, its state is lost. If it appears again, it starts from its initial value.
Let's combine several concepts from this lesson into a complete component: an input field (text state), a list (array state), adding tasks, deleting tasks, and toggling their completion. Take the time to read each function and identify the copy it creates.
import { useState } from "react";
function TaskList() {
const [text, setText] = useState("");
const [tasks, setTasks] = useState([]);
function add() {
if (text.trim() === "") {
return;
}
setTasks([...tasks, { id: Date.now(), text: text, done: false }]);
setText("");
}
function remove(id) {
setTasks(tasks.filter((task) => task.id !== id));
}
function toggle(id) {
setTasks(
tasks.map((task) =>
task.id === id ? { ...task, done: !task.done } : task
)
);
}
return (
<div>
<input
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="New task"
/>
<button onClick={add}>Add</button>
<p>{tasks.length} task(s)</p>
<ul>
{tasks.map((task) => (
<li key={task.id}>
<span
style={{
textDecoration: task.done ? "line-through" : "none",
}}
onClick={() => toggle(task.id)}
>
{task.text}
</span>
<button onClick={() => remove(task.id)}>Delete</button>
</li>
))}
</ul>
</div>
);
}
export default TaskList;tasks.length.filterandmap.Rendering the list usesmapand akeyattribute. These two concepts will be explained in the lesson about lists. For now, focus on how each action updates state and triggers a new render.
letis enough to update the screen.useStateis used on every render.pushis a good way to add an item to an array stored in state.useStateinside anifstatement.Answers: False (React is not notified); false (the initial value is used only on the first render); false (each instance has its own state); false (you must create a copy); false (hooks must be called at the top level).
use....operator, used to copy array elements or object properties.Exercise
Countercomponent with three buttons: "+", "-", and "Reset". The counter must never go below zero.import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Value: {count}</p>
<button onClick={() => setCount((previous) => previous + 1)}>+</button>
<button
onClick={() => setCount((previous) => Math.max(0, previous - 1))}
>
-
</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
}
export default Counter;Exercise 2: An Input with a Character Counter
function CharacterCounter() {
const [text, setText] = useState("");
return (
<div>
<input
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
/>
<p>{text.length} character(s)</p>
</div>
);
}Go Further
Switchcomponent with boolean state: a button that alternates between "On" and "Off" and changes the background color of a box.function Switch() {
const [isOn, setIsOn] = useState(false);
const boxStyle = {
padding: 24,
borderRadius: "12px",
backgroundColor: isOn ? "#fef08a" : "#334155",
color: isOn ? "#1e293b" : "#f8fafc",
};
return (
<div style={boxStyle}>
<p>The light is {isOn ? "on" : "off"}.</p>
<button onClick={() => setIsOn(!isOn)}>
{isOn ? "Turn off" : "Turn on"}
</button>
</div>
);
}useStatereturns the current value and a function to update it.filter, ormap.