Skip to main content

Web frameworks · Beginner · 22 min

Manage component state in React with useState

By Padding · Updated 18 Nov 2026
Node.js 26 · React 19.3 · Vite 8.3 · Vitest 5.1

You will build a small React 19 book list with a favourite toggle, an add-book form and a live filter, keep its components in sync with useState and lifted state, and prove the filter works with a Testing Library test.

On this page

A React component is a function that turns data into a piece of the page. Some of that data comes from outside, passed in by the parent as props. Some of it belongs to the component and changes while the page is open: which books are favourites, what someone has typed into a search box. That second kind is state, and useState is the hook that holds it.

In this tutorial you build a reading list with five books. You can mark favourites, add new books and filter the list as you type. Along the way you meet the habits that keep state predictable: replace values instead of changing them, use an updater function when the next value depends on the last one, keep each piece of state in the closest parent that needs it, and give list items stable keys. You finish with a test that types into the filter and checks what is on screen.

It uses the same Vite and TypeScript template as build a React 19 app with Vite, which explains the files the template creates. That background is not repeated here.

Step 1 · Create the project and start Vite

Create a fresh project in a throwaway folder and install its dependencies:

Bash
cd ~
npm create vite@9 booklist-demo -- --template react-ts --no-interactive
cd booklist-demo
npm install

Start the dev server. It keeps running, so open a second terminal in ~/booklist-demo for every command that follows:

Bash
npm run dev

Check it worked

The first terminal prints Local: http://localhost:5173/. Open that address in a browser and you see the Vite and React starter page. Leave the tab open: each time you save a file in the steps below, the page updates on its own.

Bash
curl -s http://localhost:5173/ | grep -o '<div id="root"></div>'

Step 2 · Render the books from props

Start with no state at all. The book data lives in its own module, and two components display it. BookList receives an array of books, and BookRow receives one book. Both get everything through props, so they only show what they are given.

Bash
cat > src/books.ts <<'TS'
export type Book = {
  id: number
  title: string
  author: string
  favourite: boolean
}

export const startingBooks: Book[] = [
  { id: 1, title: 'Things Fall Apart', author: 'Chinua Achebe', favourite: false },
  { id: 2, title: 'Half of a Yellow Sun', author: 'Chimamanda Ngozi Adichie', favourite: false },
  { id: 3, title: 'Petals of Blood', author: "Ngũgĩ wa Thiong'o", favourite: false },
  { id: 4, title: 'Nervous Conditions', author: 'Tsitsi Dangarembga', favourite: false },
  { id: 5, title: 'A Wizard of Earthsea', author: 'Ursula K. Le Guin', favourite: false },
]
TS
cat > src/BookList.tsx <<'TSX'
import type { Book } from './books'

function BookRow({ book }: { book: Book }) {
  return (
    <li>
      <span className="title">{book.title}</span>
      <span className="author">{book.author}</span>
    </li>
  )
}

export function BookList({ books }: { books: Book[] }) {
  if (books.length === 0) return <p>No books match.</p>
  return (
    <ul className="book-list">
      {books.map((book) => (
        <BookRow key={book.id} book={book} />
      ))}
    </ul>
  )
}
TSX
cat > src/App.tsx <<'TSX'
import { startingBooks } from './books'
import { BookList } from './BookList'
import './App.css'

export default function App() {
  return (
    <main className="books">
      <h1>Reading list</h1>
      <BookList books={startingBooks} />
    </main>
  )
}
TSX
cat > src/App.css <<'CSS'
.books {
  max-width: 34rem;
  margin: 2rem auto;
  padding: 0 1rem;
  text-align: left;
}

.book-list {
  list-style: none;
  padding: 0;
}

.book-list li {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 0.25rem 0.75rem;
  padding: 0.5rem 0;
  border-bottom: 1px solid #d9dce1;
}

.book-list .title {
  font-weight: 600;
}

.book-list .author {
  flex: 1;
  opacity: 0.7;
}

.books label {
  display: block;
  margin: 0.75rem 0;
}

.books input {
  display: block;
  width: 100%;
  margin-top: 0.25rem;
  padding: 0.4rem;
  box-sizing: border-box;
}
CSS

The key={book.id} on each row matters. When the list changes, React matches the old rows with the new ones by key, not by position. With the book's own ID as the key, a row stays attached to the same book when others are added, removed or filtered out. If you used the array index instead, filtering out the first book would give every remaining row a new key, and any state inside a row (an open menu, a half-typed note) would jump to the wrong book. Keys only need to be unique among siblings, and they should come from your data.

Check it worked

Run the type checker. It prints nothing when the code is correct:

Bash
npx tsc -b

The browser now shows the heading "Reading list" and five books, each with its author next to it. Nothing on the page reacts to clicks yet, because no component has state.

Step 3 · Add a favourite toggle with useState

Marking a favourite changes data while the page is open, so the list of books has to become state. The question is where to keep it. Only the component that owns state can change it, and the favourite count you add below sits in App, outside the list. So App owns the books, and passes both the books and a function to change them down to the list.

Update the list so each row has a toggle button that calls a function from its props:

Bash
cat > src/BookList.tsx <<'TSX'
import type { Book } from './books'

type RowProps = {
  book: Book
  onToggleFavourite: (id: number) => void
}

function BookRow({ book, onToggleFavourite }: RowProps) {
  return (
    <li>
      <span className="title">{book.title}</span>
      <span className="author">{book.author}</span>
      <button
        type="button"
        aria-pressed={book.favourite}
        aria-label={`Favourite ${book.title}`}
        onClick={() => onToggleFavourite(book.id)}
      >
        {book.favourite ? '★ Favourite' : '☆ Favourite'}
      </button>
    </li>
  )
}

type ListProps = {
  books: Book[]
  onToggleFavourite: (id: number) => void
}

export function BookList({ books, onToggleFavourite }: ListProps) {
  if (books.length === 0) return <p>No books match.</p>
  return (
    <ul className="book-list">
      {books.map((book) => (
        <BookRow key={book.id} book={book} onToggleFavourite={onToggleFavourite} />
      ))}
    </ul>
  )
}
TSX
cat > src/App.tsx <<'TSX'
import { useState } from 'react'
import { startingBooks, type Book } from './books'
import { BookList } from './BookList'
import './App.css'

export default function App() {
  const [books, setBooks] = useState<Book[]>(startingBooks)

  function toggleFavourite(id: number) {
    setBooks((previous) =>
      previous.map((book) =>
        book.id === id ? { ...book, favourite: !book.favourite } : book,
      ),
    )
  }

  const favourites = books.filter((book) => book.favourite).length

  return (
    <main className="books">
      <h1>Reading list</h1>
      <p>Favourites: {favourites}</p>
      <BookList books={books} onToggleFavourite={toggleFavourite} />
    </main>
  )
}
TSX

Three things are going on in toggleFavourite:

  • useState<Book[]>(startingBooks) returns the current array and setBooks. The <Book[]> part is a TypeScript type argument: it tells TypeScript the state is an array of Book objects and does not change what runs in the browser. The starting value is only used on the first render; after that React keeps the array between renders.
  • setBooks receives a function, (previous) => .... This is an updater function. React calls it with the latest state, even if other updates are queued in the same click, and uses what it returns as the new state. Use one whenever the new value is worked out from the old one.
  • The updater builds a new array with map, and a new object for the book that changed with { ...book, favourite: ... }. Every other book is reused as it is.

The tempting shortcut does not work:

TSX
// Wrong: changes the existing object and passes the same array back
const book = books.find((b) => b.id === id)!
book.favourite = !book.favourite
setBooks(books)

React compares the old and new state with Object.is. Passing back the same array tells it nothing changed, so it may skip the render and the button never updates. Changing objects in place also breaks anything that holds on to an older copy of the state.

favourites is not state. It is worked out from books on every render, so it can never disagree with the list. If a value can be calculated from existing state or props, calculate it instead of storing it.

Check it worked

Bash
npx tsc -b

In the browser, select the star button next to "Half of a Yellow Sun". It changes to a filled star, and the line above the list changes to "Favourites: 1". Select it again and both go back. Screen readers announce the button as a toggle that is pressed or not pressed, because of aria-pressed.

Step 4 · Add books with a controlled form

Next, a form that adds a book. The form keeps what is being typed in its own state, because no other component needs the half-finished title. It stores both fields in one object, which shows how to update objects in state:

Bash
cat > src/AddBookForm.tsx <<'TSX'
import { useState } from 'react'

type Props = {
  onAdd: (title: string, author: string) => void
}

export function AddBookForm({ onAdd }: Props) {
  const [draft, setDraft] = useState({ title: '', author: '' })

  function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const title = draft.title.trim()
    const author = draft.author.trim()
    if (title === '' || author === '') return
    onAdd(title, author)
    setDraft({ title: '', author: '' })
  }

  return (
    <form onSubmit={handleSubmit}>
      <h2>Add a book</h2>
      <label>
        Title
        <input
          value={draft.title}
          onChange={(event) => setDraft({ ...draft, title: event.target.value })}
        />
      </label>
      <label>
        Author
        <input
          value={draft.author}
          onChange={(event) => setDraft({ ...draft, author: event.target.value })}
        />
      </label>
      <button type="submit">Add book</button>
    </form>
  )
}
TSX
cat > src/App.tsx <<'TSX'
import { useState } from 'react'
import { startingBooks, type Book } from './books'
import { BookList } from './BookList'
import { AddBookForm } from './AddBookForm'
import './App.css'

export default function App() {
  const [books, setBooks] = useState<Book[]>(startingBooks)

  function toggleFavourite(id: number) {
    setBooks((previous) =>
      previous.map((book) =>
        book.id === id ? { ...book, favourite: !book.favourite } : book,
      ),
    )
  }

  function addBook(title: string, author: string) {
    setBooks((previous) => {
      const id = Math.max(0, ...previous.map((book) => book.id)) + 1
      return [...previous, { id, title, author, favourite: false }]
    })
  }

  const favourites = books.filter((book) => book.favourite).length

  return (
    <main className="books">
      <h1>Reading list</h1>
      <p>Favourites: {favourites}</p>
      <BookList books={books} onToggleFavourite={toggleFavourite} />
      <AddBookForm onAdd={addBook} />
    </main>
  )
}
TSX

The inputs are controlled: value comes from state, and onChange writes each keystroke back. The state is the single source of truth, which is why clearing the form is one line, setDraft({ title: '', author: '' }). Each onChange copies the whole draft with ...draft and replaces one field. If you wrote setDraft({ title: event.target.value }), the author would disappear from state.

addBook uses an updater function too, and here it prevents a real bug. Suppose you later add a button that inserts two sample books in one click by calling addBook twice. With setBooks([...books, newBook]), both calls would read the same books from the current render, and the second call would overwrite the first, leaving only one new book. The updater receives the result of the first call, so both books are kept.

Check it worked

Bash
npx tsc -b

In the browser, type a title and an author under "Add a book" and select "Add book". The book appears at the bottom of the list with its own star button, and both fields empty. Submitting with either field blank does nothing.

Step 5 · Filter the list and lift state up

The filter box and the book list are separate components, but they depend on each other: the list must show only what matches the text in the box. If the filter text lived inside the filter component, the list could not read it, because state is private to the component that declares it. The fix is to lift the state up to the closest common parent, App, and pass it down to both.

First, a helper that decides whether a book matches. It ignores case and accents, so someone typing ngugi on a phone keyboard without the tilde keys still finds Ngũgĩ wa Thiong'o. normalize('NFD') splits each accented letter into a plain letter and a separate accent mark, and the regular expression removes the marks:

Bash
cat >> src/books.ts <<'TS'

function simplify(text: string): string {
  return text.normalize('NFD').replace(/\p{Diacritic}/gu, '').toLocaleLowerCase()
}

export function matches(book: Book, query: string): boolean {
  return simplify(`${book.title} ${book.author}`).includes(simplify(query.trim()))
}
TS

Now the filter component. It holds no state of its own. It shows the value it is given and reports changes upwards:

Bash
cat > src/FilterBox.tsx <<'TSX'
type Props = {
  query: string
  onQueryChange: (query: string) => void
}

export function FilterBox({ query, onQueryChange }: Props) {
  return (
    <label>
      Filter by title or author
      <input
        type="search"
        value={query}
        onChange={(event) => onQueryChange(event.target.value)}
      />
    </label>
  )
}
TSX
cat > src/App.tsx <<'TSX'
import { useState } from 'react'
import { startingBooks, matches, type Book } from './books'
import { BookList } from './BookList'
import { AddBookForm } from './AddBookForm'
import { FilterBox } from './FilterBox'
import './App.css'

export default function App() {
  const [books, setBooks] = useState<Book[]>(startingBooks)
  const [query, setQuery] = useState('')

  function toggleFavourite(id: number) {
    setBooks((previous) =>
      previous.map((book) =>
        book.id === id ? { ...book, favourite: !book.favourite } : book,
      ),
    )
  }

  function addBook(title: string, author: string) {
    setBooks((previous) => {
      const id = Math.max(0, ...previous.map((book) => book.id)) + 1
      return [...previous, { id, title, author, favourite: false }]
    })
  }

  const visible = books.filter((book) => matches(book, query))
  const favourites = books.filter((book) => book.favourite).length

  return (
    <main className="books">
      <h1>Reading list</h1>
      <p>Favourites: {favourites}</p>
      <FilterBox query={query} onQueryChange={setQuery} />
      <p role="status">
        Showing {visible.length} of {books.length}
      </p>
      <BookList books={visible} onToggleFavourite={toggleFavourite} />
      <AddBookForm onAdd={addBook} />
    </main>
  )
}
TSX

App now holds two pieces of state, books and query, and everything else is calculated from them during render. visible is never stored, so there is no second copy of the list to keep in step. Filtering never removes anything from books: when the filter is cleared, every book comes back with its favourite intact. Because the counter has role="status", screen readers read out the new count after someone types.

Filtering a few hundred books on every keystroke is quick, even on a low-end Android phone. With many thousands of items you would look at deferring the filter, but measure first.

Check it worked

Bash
npx tsc -b

In the browser, mark "Half of a Yellow Sun" as a favourite, then type achebe into the filter box. Only "Things Fall Apart" is listed and the counter reads "Showing 1 of 5". Type ngugi and "Petals of Blood" appears. Clear the box: all five books return, and "Half of a Yellow Sun" still has its filled star.

Step 6 · Test the filter with Testing Library

Clicking through the page after every change gets old. Testing Library renders a component into a simulated browser page (jsdom) and lets the test find elements the way a person would, by their labels and text. Vitest runs the tests and reuses the project's Vite settings. Install them as development dependencies, at the versions this tutorial was written with, and add a test script:

Bash
npm install --save-dev vitest@5.1.1 jsdom@31.0.1 @testing-library/react@16.3.3 @testing-library/dom@10.4.2 @testing-library/user-event@14.6.13
npm pkg set scripts.test="vitest run"

Write a test file next to App.tsx:

Bash
cat > src/App.test.tsx <<'TSX'
// @vitest-environment jsdom
import { afterEach, describe, expect, it } from 'vitest'
import { cleanup, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import App from './App'

afterEach(cleanup)

describe('book filter', () => {
  it('shows only the books that match', async () => {
    const user = userEvent.setup()
    render(<App />)
    await user.type(screen.getByLabelText('Filter by title or author'), 'Achebe')
    expect(screen.getAllByRole('listitem')).toHaveLength(1)
    expect(screen.getByText('Things Fall Apart')).toBeTruthy()
    expect(screen.getByRole('status').textContent).toBe('Showing 1 of 5')
  })

  it('ignores accents in names', async () => {
    const user = userEvent.setup()
    render(<App />)
    await user.type(screen.getByLabelText('Filter by title or author'), 'ngugi')
    expect(screen.getByText('Petals of Blood')).toBeTruthy()
  })

  it('keeps favourites when the filter is cleared', async () => {
    const user = userEvent.setup()
    render(<App />)
    const star = screen.getByRole('button', { name: 'Favourite Half of a Yellow Sun' })
    await user.click(star)
    const filter = screen.getByLabelText('Filter by title or author')
    await user.type(filter, 'earthsea')
    expect(screen.queryByText('Half of a Yellow Sun')).toBeNull()
    await user.clear(filter)
    expect(screen.getAllByRole('listitem')).toHaveLength(5)
    expect(
      screen.getByRole('button', { name: 'Favourite Half of a Yellow Sun' }).getAttribute('aria-pressed'),
    ).toBe('true')
  })
})
TSX

The comment on the first line tells Vitest to run this file in jsdom, so no extra configuration file is needed. afterEach(cleanup) removes the rendered page between tests; Testing Library only does that by itself when test globals are switched on. userEvent types one character at a time and fires the same events a browser would, so each keystroke goes through onChange and setQuery exactly as it does for a real user. The third test checks the point of lifting state up: hiding a book with the filter does not lose its favourite.

Run the tests:

Bash
npm test

Check it worked

Vitest ends with a summary along the lines of Test Files 1 passed (1) and Tests 3 passed (3). To see a failure, change 'Showing 1 of 5' to 'Showing 2 of 5' in the test and run npm test again: Vitest prints the expected and received text side by side. Change it back afterwards.

Step 7 · Build the app and clean up

Stop the dev server with Ctrl+C in its terminal.

Build the production version. The build runs the TypeScript checker over every file in src, including the test, before Vite bundles the app:

Bash
npm run build
ls dist

Check it worked

The build ends with built in and a time, and dist contains index.html, an assets folder and the files copied from public. The test file is type-checked but not bundled, because nothing in the app imports it.

When you have finished experimenting, remove the project:

Bash
cd ~
rm -rf ~/booklist-demo

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.