Skip to content
Qyubie Learn
Web Development courseLesson 13 of 20 · tap to see all lessons

Web Development · Beginner

React State and Interaction: useState, Events, Conditional Rendering, Lists, Forms, and useEffect

Make React components interactive: remember data with useState, handle events, render conditionally, show lists with keys, build controlled forms, and use useEffect.

  • Qyubie Learn Editorial Team
  • Published
  • 20 min read

Includes 2 exercises and 2 quick checks you can do right here.

The components in lesson 12 always showed the same thing for the same props. Real interfaces change: a counter goes up, a menu opens, a list grows as you add to it, a form fills in as you type. In React, data that changes over time is called state. When state changes, React runs your component again and updates the page to match. You never touch the DOM yourself.

By the end of this lesson you will be able to:

  • store and update data with the useState hook,
  • handle clicks, typing, and form submits,
  • show or hide parts of the page with conditional rendering,
  • render lists from arrays with keys, and add or remove items,
  • build controlled forms, and
  • explain what useEffect is for, and use it to load data.

All the examples use the same browser setup as lesson 12 (the import map, Babel, and <script type="text/babel" data-type="module">). It needs an internet connection.

State and useState

A normal variable inside a component doesn't work for changing data: it's created fresh every time the component runs, and changing it doesn't tell React to update the page. useState solves both problems:

import React, { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <button onClick={() => setCount(count + 1)}>
      Clicked {count} times
    </button>
  );
}

useState(0) returns a pair, which you destructure:

  • count: the current value (it starts at 0, the initial value),
  • setCount: the function that changes it. Calling it stores the new value and tells React to re-render (run the component again), so the page shows the new number.

Functions whose names start with use are called hooks. Two rules: call them only at the top level of a component (not inside if, loops, or nested functions), and only in components (or other hooks).

Try it · HTML & CSS

Preview (index.html, updates as you type)

Click the two counters: each keeps its own state. State belongs to each copy of a component, not to the function. Notice also that disabled={count === 0} updates by itself; you describe the result, React keeps it true.

Updating based on the previous value

setCount(count + 1) uses the count from the current render. Calling it twice in one click still adds only 1, because both calls see the same old count. When the new value depends on the old one, pass a function; React gives it the latest value:

function addTwo() {
  setCount((c) => c + 1);
  setCount((c) => c + 1); // now this really adds 2
}

Quick check

What does the button show after one click?
function Counter() {
  const [count, setCount] = useState(5);
  function handleClick() {
    setCount(count + 1);
    setCount(count + 1);
  }
  return <button onClick={handleClick}>{count}</button>;
}

Events

React events look like HTML event attributes, written in camelCase, and you pass a function (not a string, and not a call):

EventFires when
onClickan element is clicked
onChangean input, select, or textarea changes (on every keystroke)
onSubmita form is submitted
onMouseEnter, onFocus, onKeyDownhover, focus, key press
<>
  <button onClick={handleClick}>Save</button>          {/* ✓ passes the function */}
  <button onClick={() => remove(id)}>Delete</button>   {/* ✓ arrow function, for arguments */}
  <button onClick={handleClick()}>Save</button>        {/* ✗ calls it during render */}
</>

The handler receives an event object, like in lesson 7. event.target.value is what's in an input, and event.preventDefault() stops a form from reloading the page.

Conditional rendering

Since a component is a function, you decide what to show with ordinary JavaScript:

PatternUse it when
{isOpen && <Menu />}show something or nothing
{loggedIn ? <Logout /> : <Login />}choose between two things
if (...) return <Spinner />; before the main returna whole different screen

This password field combines state, an event, and both patterns:

Try it · HTML & CSS

Preview (index.html, updates as you type)

One trap with &&: if the left side is the number 0, React prints 0. Write {items.length > 0 && <List />}, not {items.length && <List />}.

Lists, keys, and rendering data

To show an array, turn each item into JSX with map. Each item needs a key: a value that's unique among its siblings and doesn't change, usually the item's database id. React uses keys to tell which item is which when the list changes.

const students = [
  { id: 1, name: "Ana Reyes", course: "BSCS" },
  { id: 2, name: "Ben Cruz", course: "BSIT" },
];

<ul>
  {students.map((s) => (
    <li key={s.id}>{s.name} ({s.course})</li>
  ))}
</ul>

Avoid using the array index as the key when items can be added, removed, or reordered; React can mix up which row is which.

Changing arrays in state

Never change a state array in place (push, splice, assigning list[0] = ...): React compares the old and new value, sees the same array, and may not update. Always make a new array:

ToWrite
addsetTasks([...tasks, newTask])
removesetTasks(tasks.filter((t) => t.id !== id))
change onesetTasks(tasks.map((t) => (t.id === id ? { ...t, done: !t.done } : t)))

Here's the to-do list from lesson 7, now in React. Compare how much shorter it is when you don't manage the DOM yourself:

Try it · HTML & CSS

Preview (index.html, updates as you type)

The "left to do" count isn't stored in state; it's calculated from tasks on every render. Store the smallest amount of state you can and derive the rest.

Quick check

Which correctly adds item to the cart state array?

Controlled forms

In a controlled input, React state is the single source of truth: the input's value comes from state, and onChange updates that state. That way you always know what's in the form, and you can validate, reset, or transform it easily.

For a form with many fields, keep one state object and update the field whose name matches:

Try it · HTML & CSS

Preview (index.html, updates as you type)

Key points:

  • [name]: value is a computed property: it sets whichever field changed, so one handleChange serves every input.
  • Checkboxes use checked, not value.
  • event.preventDefault() stops the browser's normal submit, so React handles it. Later, the submit handler is where you'll send the data to an API (lesson 15) or a database (lesson 16).

useEffect: syncing with the outside world

Rendering should only calculate JSX. Some work has to happen outside that calculation: loading data from an API, starting a timer, changing the page title. useEffect runs that kind of code after React has updated the page.

useEffect(() => {
  // runs after render
  return () => {
    // optional cleanup: runs before the effect runs again, and when the component is removed
  };
}, [dependencies]);

The dependency array controls when it runs:

Second argumentThe effect runs
[]once, after the first render
[userId]after the first render, and again whenever userId changes
(left out)after every render (rarely what you want)

The most common use is loading data when a component appears. This one fetches users from a public test API (from lesson 10), with loading and error states:

Try it · HTML & CSS

Preview (index.html, updates as you type)

Notes:

  • The effect function itself can't be async, so it defines an async function inside and calls it.
  • The empty [] means "load once". Without it, setUsers would re-render, the effect would run again, and it would fetch forever.
  • In development, React's Strict Mode runs effects twice on purpose to catch missing cleanups, so you may see two requests. That's expected.

Don't reach for useEffect by default. If a value can be calculated from props or state (a total, a filtered list, a full name), calculate it during render, like left in the to-do list. If something should happen because the user clicked, put it in the event handler. Effects are for syncing with things outside React. In Next.js (lesson 14), you'll often load data on the server instead, without an effect at all.

Exercise · HTML & CSS

Like button with state

Make a LikeButton component. It shows 🤍 Like and a count of 0. Each click toggles between liked and not liked: when liked, the button shows ❤️ Liked and the count is 1; clicking again goes back. Use useState and onClick.

Preview (index.html, updates as you type)
Hint

const [liked, setLiked] = useState(false); then onClick={() => setLiked(!liked)}, show {liked ? "❤️ Liked" : "🤍 Like"} and {liked ? 1 : 0}.

Show a solution

Try it yourself first — you learn more from a wrong attempt than from reading an answer.

<div id="root"></div>

<script type="importmap">
  { "imports": {
    "react": "https://esm.sh/react@19.3.1",
    "react-dom/client": "https://esm.sh/react-dom@19.3.1/client?external=react"
  } }
</script>
<script src="https://unpkg.com/@babel/standalone@7/babel.min.js"></script>

<script type="text/babel" data-type="module">
  import React, { useState } from "react";
  import { createRoot } from "react-dom/client";

  function LikeButton() {
    const [liked, setLiked] = useState(false);
    return (
      <p>
        <button onClick={() => setLiked(!liked)}>
          {liked ? "❤️ Liked" : "🤍 Like"}
        </button>{" "}
        {liked ? 1 : 0} likes
      </p>
    );
  }

  createRoot(document.getElementById("root")).render(<LikeButton />);
</script>

Exercise · HTML & CSS

Filter students by grade

Add a controlled number input for a minimum grade (start at 80). Show only the students whose grade is at least that value, as a list with key={s.id}, and show No students match. when none do.

Preview (index.html, updates as you type)
Hint

const [min, setMin] = useState(80); const shown = students.filter((s) => s.grade >= min); then <input type="number" value={min} onChange={(e) => setMin(Number(e.target.value))} /> and shown.map((s) => <li key={s.id}>...</li>).

Show a solution

Try it yourself first — you learn more from a wrong attempt than from reading an answer.

<div id="root"></div>

<script type="importmap">
  { "imports": {
    "react": "https://esm.sh/react@19.3.1",
    "react-dom/client": "https://esm.sh/react-dom@19.3.1/client?external=react"
  } }
</script>
<script src="https://unpkg.com/@babel/standalone@7/babel.min.js"></script>

<script type="text/babel" data-type="module">
  import React, { useState } from "react";
  import { createRoot } from "react-dom/client";

  const students = [
    { id: 1, name: "Ana", grade: 92 },
    { id: 2, name: "Ben", grade: 74 },
    { id: 3, name: "Cara", grade: 85 },
    { id: 4, name: "Dan", grade: 70 },
  ];

  function GradeFilter() {
    const [min, setMin] = useState(80);
    const shown = students.filter((s) => s.grade >= min);

    return (
      <div>
        <label>
          Minimum grade{" "}
          <input type="number" value={min} onChange={(e) => setMin(Number(e.target.value))} />
        </label>
        {shown.length === 0 ? (
          <p>No students match.</p>
        ) : (
          <ul>
            {shown.map((s) => (
              <li key={s.id}>{s.name}: {s.grade}</li>
            ))}
          </ul>
        )}
      </div>
    );
  }

  createRoot(document.getElementById("root")).render(<GradeFilter />);
</script>

Common mistakes

  • Changing state directly (count++, tasks.push(...)) instead of calling the setter with a new value.
  • Calling a handler during render: onClick={save()} instead of onClick={save} or onClick={() => save(id)}.
  • Missing or unstable keys, which gives a console warning and confused list updates.
  • A value without onChange, which makes an input you can't type in.
  • Forgetting preventDefault() in onSubmit, so the page reloads.
  • A useEffect with no dependency array that sets state: an endless loop of renders.
  • Storing what you can calculate (a total, a filtered list) in its own state.

Summary

  • State is a component's memory. const [value, setValue] = useState(initial); calling the setter re-renders the component. Use setValue((old) => ...) when the new value depends on the old.
  • Events take functions: onClick, onChange, onSubmit.
  • Conditional rendering uses &&, ? :, or an early return.
  • Lists use map with a stable, unique key; change state arrays by making new ones with spread, filter, and map.
  • Controlled forms keep every input's value in state.
  • useEffect syncs with the outside world after render, controlled by its dependency array; use it sparingly.

Next: Next.js, which turns React components into a complete website with pages, layouts, and routes, styled with Tailwind CSS.

References and further reading