Lesson 6 / 1155%

Lesson 6

State with useState

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

  • Explain why an ordinary variable is not enough to remember data that changes.
  • Create and read state using useState.
  • Update state using its setter function, including updates based on the previous value.
  • Manage text, boolean, object, and array state without modifying them directly.
  • Follow the rules of hooks and identify common mistakes.

Why Do We Need State?

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.

A Counter That Does Not Work

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.

incorrect: an ordinary variable
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.

Cycle diagram: User action (click) → state update → React re-renders the component → updated interface appears → user interacts again.

The state cycle: action, update, re-render, and another action.

The useState Hook

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.

a counter
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.

Array Destructuring and Naming

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.

the same thing without destructuring
// 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.

GIF of the Counter component: the button is clicked several times, and the displayed number increases with each click.

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.

Which Initial Value Should You Choose?

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.

different types of state
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 }); // object
  • Number: counters, quantities, scores, pages.
  • Text: input field content or a message.
  • Boolean: information with two possible values, such as an open or closed menu or a checked or unchecked box.
  • Array: a list of items that grows or shrinks.
  • Object: several related pieces of information, such as the fields of a profile.

State Is a Snapshot of Each Render

Here 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.

the value does not change immediately
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.

Calculating New State from Previous State

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:

functional update
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.

two consecutive updates: comparison
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.

Multiple State Variables and Complex State

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.

updating an object and an array
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.

Three Operations on an Array

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.

adding, removing, and updating array items
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
    )
  );
}
  • Add: instead ofpush, create a new array using[...previous, newItem].
  • Remove: instead ofsplice, usefilter.
  • Update: instead of directly assigning a value to an item, usemapand 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.

Objects: Updating a Single Property

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.

replacing an object property
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.

Example: An Input Field

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.

a controlled input field
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.

Example: A Boolean for Opening and Closing

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.

a menu that opens and closes
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.

Do Not Store What You Can Calculate

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.

calculate instead of duplicating
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.

The Rules of Hooks

  • Call hooks at the top level of a component, not inside a condition, loop, or nested function.
  • Call them only inside React componentsor your own custom hooks.

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, then correct
// 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.

Common Mistakes

  • Modifying state directly: writingcount = 5does not trigger a new render.
  • Modifying an array in place: usingpushon a state array is not the correct approach. Create a new array instead.
  • Forgetting the import: withoutimport { useState } from "react", the hook is not defined.
  • Calling a hook inside a condition: always place it at the top level of the component.
  • Expecting the new value immediately after an update: inside the same function, the variable still contains the previous value.
  • Writing onClick={setCount(1)}: with parentheses, the update runs during rendering and can cause an infinite loop. Instead, writeonClick={() => setCount(1)}.
  • Forgetting the spread operator in an object: without it, the object's other properties disappear from the new state.

Each Component Has Its Own State

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.

two independent counters
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.

Mini Project: A To-Do List

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.

to-do list: text state and array state
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;
  • Two state variables: a string for the input and an array for the list. Each piece of information has its own state.
  • The number of tasks is not state: it is calculated usingtasks.length.
  • Add: copy the array using the spread operator, then clear the input field.
  • Delete and toggle: create new arrays usingfilterandmap.

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.

True or False?

  • A variable declared withletis enough to update the screen.
  • The value passed touseStateis used on every render.
  • Two instances of the same component share the same state.
  • pushis a good way to add an item to an array stored in state.
  • You can calluseStateinside 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).

Quick Glossary

  • State: a component's memory, which can change over time.
  • Hook: a special React function whose name begins withuse.
  • Re-render: React running a component again after a state change.
  • Spread: the...operator, used to copy array elements or object properties.
  • Controlled input: an input field whose value is stored in state.

Exercises

Exercise

Create aCountercomponent with three buttons: "+", "-", and "Reset". The counter must never go below zero.
suggested solution for exercise 1
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

Create a text input that displays the number of entered characters underneath it. Use only one state variable and calculate the length directly.
suggested solution for exercise 2
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

Create aSwitchcomponent with boolean state: a button that alternates between "On" and "Off" and changes the background color of a box.
suggested solution for Go Further
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>
  );
}

Key Takeaways

  • State is a component's memory. When it changes, React re-renders the component.
  • useStatereturns the current value and a function to update it.
  • Never modify state directly. Always use the setter function.
  • When new state depends on previous state, pass a function to the setter.
  • For objects and arrays, create copies using the spread operator,filter, ormap.
  • Do not store values in state if they can be calculated from other state variables.
  • Call hooks at the top level, only inside React components or custom hooks.