Learnings

Tutorial 2 of 6

React Practice: Usage Examples and Exercises

Worked usage examples and exercises with hidden solutions for everything in React Essentials: state, effects, hooks, composition, routing and testing, ending with three small bank projects. Every example was type-checked, and most come with a Testing Library test that was run, on React 19.3, React Router 7 and Vitest 4.

How to use this page

Part 1 of 8 · the project, the routine and the list

Usage examples are worked in the open: read them, run them, change them. Exercises hide the solution: write your own first.

The practice project

How to use this page

One Vite project holds every example. Each example lists its files with their paths; drop them in, run the test, delete them or keep them in a folder. These commands were run as shown.

Vitest needs a browser-like DOM (jsdom) and the extra matchers such as toBeInTheDocument:

Most examples use the same bank data and one formatting helper. Create this file once:

Versions: React 19.3, react-router-dom 7.18, TypeScript 7, Vitest 4. The Vite template's tsconfig.app.json rejects unused variables and parameters, needs import type for type-only imports and forbids enum, so every example is written that way.

The routine

How to use this page

  • Try for 10 to 15 minutes before opening a solution. Being stuck for a while is what makes the solution stick.
  • Make the behaviour list pass. Each exercise says what the finished thing must do. Most solutions come with a test that checks exactly that list: paste it next to your code and run it against your own version.
  • Puzzles ("predict the output", "spot the bug") have no code to write. Write your answer down, then open the solution. Their tests prove the answer on the real library.
  • To see a component, render it from src/App.tsx.

Everything on this page

How to use this page

"Example" rows are worked usage examples; numbered rows are exercises.

#ItemLevelDrills
ExampleDerived state, not duplicated stateeasycomputing during render
ExampleImmutable updateseasyarrays and nested objects
1Three setCount callseasy, puzzlesnapshots, batching, updaters
2The stray 0easy, bug&& with numbers
3Lift state upeasyshared state in the parent
4Index keysmedium, puzzlekeys and component state
5Form with validationmediumcontrolled inputs, errors, useId
ExampleYou may not need an effecteasyreset with key
ExampleFetch with loading, error and abortmediumstatus union, mocked fetch
ExampleEvent listener cleanupeasyeffect cleanup
6Two requests racemedium, puzzleout-of-order responses
7The frozen tickermedium, puzzlestale closures
8Debounced searchmediumtimers, abort, cleanup
ExampleThree small custom hookseasyrenderHook, localStorage
ExampleuseRef twiceeasyDOM focus, mutable value, ref as a prop
ExampleReact 19 hooksmediumuseActionState, use, useTransition
9useFetch with abortmediumgeneric hook and its test
10Account with useReducermediumdiscriminated-union actions
11What re-renders?hard, puzzlememo, useCallback
ExampleChildren, slots and render propseasygeneric components
ExampleError boundary and lazy loadingmediumclass boundary, Suspense, lazy
12Stop the prop drillingeasycontext, throwing hook
13Compound Tabsmediumcontext inside a component family
ExampleNested routesmediumOutlet, params, not found
14Filter in the URLmediumuseSearchParams
15Protected routemediumredirect and come back
ExampleTesting toolboxmediumqueries, vi.mock
16Write the testmediumuser events, assertions
17Six problems, one componenthard, bugeverything above
ExamplePerformance and correctness habitsreferencerules of thumb
18Accounts dashboardprojectuseReducer + context, filter, sort
19Transfer with rollbackprojectuseOptimistic, validation
20Transactions tableprojectURL search params, pagination

State and events

Part 2 of 8 · what to store, how to change it

Most React bugs are state bugs: storing something that could be computed, changing it in place, or reading a value that is a snapshot.

Example: derived state, not duplicated state

State and events

A filtered list and its total can always be computed from the accounts and the query, so they are not state. Store the minimum (the query) and compute the rest on every render. The version people write first stores them and keeps them in sync with an effect:

What to notice

  • The test for state should be: "can I compute this from props or other state?" If yes, compute it.
  • Interview point: "copying props into state" is the classic bug. The copy does not update when the prop changes.

Example: immutable updates

State and events

React compares state by reference. Changing an array or object in place keeps the same reference, so React sees no change. Each update below returns a new value and copies only what is on the path to the change.

TaskWriteNot
Add[...list, item]list.push(item)
Removelist.filter((a) => a.id !== id)list.splice(i, 1)
Change one itemlist.map((a) => a.id === id ? { ...a, balance } : a)list[i].balance = balance
Sortlist.toSorted(cmp)list.sort(cmp)
Insert at ilist.toSpliced(i, 0, item)list.splice(i, 0, item)
Nested field{ ...p, address: { ...p.address, city } }p.address.city = city

What to notice

  • Unchanged items keep their identity (next[0] === accounts[0]). That is what lets memo skip rows that did not change (exercise 11).
  • toSorted, toSpliced, toReversed and with(i, value) are the ES2023 copying versions of the mutating array methods.

1. Three setCount calls

State and events · easy, predict the output

The button is clicked once. What does it show, and what does console.log print? Then: what changes after a second click?

Hints

  • What is the value of count inside this call of handleClick? Can anything change it before the function returns?
  • React does not re-render after each setter call; it batches them until the handler ends.
Solution

One click shows 1 and logs 0. The second click shows 2 and logs 1. count is a constant for the whole render, so all three calls say "set it to 0 + 1". The log runs before the re-render, so it prints the old snapshot. This test proves it:

To add three, pass an updater function. React queues the updaters and runs each one on the result of the previous one:

  • Rule: when the new state depends on the old state, use the updater form. It is never wrong.
  • Since React 18, batching also applies inside setTimeout, promises and native event handlers, not only React events.

2. The stray 0

State and events · easy, spot the bug

With pending={2} this shows "Inbox (2 pending)". With pending={0} the product owner sees "Inbox0". Find the cause and fix it.

Hints

  • What does 0 && anything evaluate to in JavaScript?
  • React renders nothing for false, null and undefined. What does it do with a number?
Solution

0 && x is 0, and React renders numbers. Make the left side a real boolean:

  • Same trap with list.length &&. Write list.length > 0 &&, !!count &&, or a ternary.

3. Lift state up

State and events · easy

Build AccountsPanel from two child components: AccountPicker, a list of buttons with one per owner, and AccountDetails, which shows the selected account. The two children are siblings, so neither can own the selection.

  • Before any click, the details area says "Select an account".
  • Clicking "Subhash Agrawani" shows a heading with that name and "Balance: ₹12,000".
  • The selected button has aria-pressed="true"; the others "false".

Hints

  • State lives in the closest common parent. The picker gets the selected id and an onSelect callback.
  • Store the id, not a copy of the account object. Find the account during render.
Solution
  • Storing the id means the details always show the latest balance, even after a deposit changes the account object.
  • onSelect={setSelectedId} passes the setter directly: its identity never changes, which matters in exercise 11.

4. Index keys

State and events · medium, predict the output

Each row keeps its own note in state. You type "x" into the note for a, then click "Remove first". Row a disappears. What is in the note box of row b now?

Hints

  • React matches old and new children by key. Which key did row a have, and which row has that key after the removal?
  • State belongs to a position in the tree, identified by key, not to the data.
Solution

Row b shows "x". Before: keys 0, 1, 2 for a, b, c. After: keys 0, 1 for b, c. React keeps the component with key 0 (and its note "x"), gives it the label b, and removes key 2.

The fix is one word: key by something that belongs to the item. With it, the same test finds an empty note for b.

  • Index keys are safe only for lists that never reorder, insert or delete, and whose rows hold no state (inputs count).
  • Keys must be stable and unique among siblings. Database ids are ideal; Math.random() is the worst choice, it remounts every row on every render.

5. Form with validation

State and events · medium

Write OpenAccountForm with two controlled inputs, "Owner" and "Opening deposit", and a submit button "Open account". It calls onSubmit({ owner, deposit }) only when both fields are valid.

  • Owner: at least 3 characters after trimming, else "Owner needs at least 3 characters".
  • Deposit: a whole number of at least 500, else "Opening deposit is at least ₹500".
  • Errors appear after a submit attempt, each in an element with role="alert", and are linked to their input with aria-describedby (so a screen reader reads them with the field).
  • A valid submit sends the trimmed owner and the deposit as a number.

Hints

  • Write validate(owner, deposit) as a plain function that returns an errors object. Easy to test, easy to reuse on blur.
  • useId() gives ids that are unique even if the form appears twice on the page.
  • Add noValidate to the form if you also use HTML attributes like required, or the browser's own bubbles get in first.
Solution
  • Inputs hold strings. Keep the raw string in state and convert at the edge (Number(deposit) on submit), or "1e3" and "" sneak through as numbers.
  • In @types/react 19.3 the form event type is SubmitEvent; FormEvent still compiles but is marked deprecated.

Effects

Part 3 of 8 · syncing with the world outside React

An effect is for talking to something React does not control: the network, timers, the DOM, browser storage. Every effect that starts something must stop it in its cleanup.

Example: you may not need an effect

Effects

If an effect only sets state from other state or props, it is not syncing with anything outside React: it is an extra render with a frame of wrong data. The usual replacements:

You wrote an effect to...Do this instead
compute a value from props or statecompute it during render (derived state)
cache an expensive computationuseMemo(() => compute(a), [a])
react to a click or submitdo it in the event handler
reset state when a prop changesgive the component a key (below)
tell the parent about a changecall the parent's callback in the same handler
fetch dataan effect is fine (with cleanup), or a data library or router loader

Here a draft note must be cleared when the user switches account. The effect version resets it one render late:

What to notice

  • key is not only for lists. On any element it means "this is a different thing now".
  • Interview point: React's docs have a whole page called "You Might Not Need an Effect". Knowing the table above is a strong signal.

Example: fetch with loading, error and abort

Effects

The Essentials fetch example uses three separate pieces of state. One status union makes impossible combinations (loading and error at once) impossible to write, and checking res.ok turns a 503 into an error instead of trying to parse an error page as JSON.

The test replaces the global fetch with a mock and waits for the result with a findBy query, which retries until the element appears (default 1 second):

What to notice

  • In development, Strict Mode mounts, unmounts and mounts again, so you see two requests and the first one aborted. That is the cleanup being tested, not a bug.
  • vi.unstubAllGlobals() in afterEach puts the real fetch back so tests cannot leak into each other.

Example: event listener cleanup

Effects

A dialog that closes on Escape listens on document, which React does not manage. Without the cleanup, every time the dialog opens another listener piles up, and old ones call a stale onClose.

Effect startsCleanup stops
addEventListener(type, fn)removeEventListener(type, fn) with the same function
setInterval / setTimeoutclearInterval / clearTimeout
fetch(url, { signal })controller.abort()
a WebSocket or subscriptionsocket.close() / unsubscribe()
new ResizeObserver(cb).observe(el)observer.disconnect()

6. Two requests race

Effects · medium, predict the output, then fix

The user opens account 1, then quickly account 2, so id goes 1 then 2. The server answers for 2 first, and the slow answer for 1 arrives last. Whose account is on screen at the end? Then fix the component.

  • After the fix, the last response to arrive cannot overwrite a newer id.
  • While a new id is loading, the old account is not shown under the new id.
  • Unmounting or changing id cancels the request in flight.

Hints

  • Each run of the effect has its own closure. The cleanup of run 1 executes before run 2 starts.
  • Remember which id a result belongs to; then "loading" is just "the result is for a different id".
Solution

The screen shows Rishikesh Agrawani (account 1) while the prop says 2: whichever response arrives last wins. Fix: a per-run ignore flag set in the cleanup, plus an abort so the stale request stops using the network.

The test controls when each response arrives. The mock returns a promise and keeps its resolve function per URL:

  • The abort alone is not enough in general: a response can resolve between the abort and your .then. The flag is what guarantees correctness; the abort saves bandwidth.
  • Run this test against the buggy version and it fails with "Rishikesh Agrawani". That is how to know a test covers a bug.

7. The frozen ticker

Effects · medium, predict the output, then fix

This should count seconds. What does it show after 5 seconds? Fix it without adding seconds to the dependency array.

Hints

  • The interval callback was created during the first render. Which seconds does it see, forever?
  • Adding seconds to the deps "works" but tears down and recreates the interval every second.
Solution

It shows 1 s forever. The callback closes over seconds = 0 from the first render, so every tick sets 0 + 1. Fake timers make the test instant:

The updater form reads the current value from React instead of from the closure; with it the same test shows "5 s":

  • If the callback must read a prop (say a step size) without restarting the interval, React 19.2+ has useEffectEvent for exactly that; it is exported by the installed 19.3.

8. Debounced search

Effects · medium

Write AccountSearch: a search box (accessible name "Search accounts") that calls GET /api/accounts?q=... and lists the owners returned. Typing "san" quickly must make one request, not three.

  • The request goes out 300 ms after the last keystroke, with the query URL-encoded.
  • An empty box makes no request and shows no results.
  • A request still in flight when the query changes is aborted.

Hints

  • Start a setTimeout in the effect and clear it in the cleanup. Each keystroke cancels the previous timer.
  • The same cleanup can abort the fetch.
Solution

Hooks

Part 4 of 8 · custom hooks, refs, reducers, memoisation, React 19

Custom hooks reuse logic, refs hold what must not re-render, reducers keep state transitions in one pure function.

Example: three small custom hooks

Hooks

Each hook is a function that calls other hooks and returns what the component needs. as const makes the return a tuple, so callers can name the parts like useState.

renderHook runs a hook inside a throwaway component; result.current is its latest return value:

What to notice

  • useState(() => ...) runs the function on the first render only. useState(read()) would read storage on every render and ignore the result.
  • Two components using useLocalStorage("x") each get their own state; a hook shares logic, not state. Shared state needs context or a store.

Example: useRef twice

Hooks

A ref is a box (ref.current) that survives renders, and changing it does not re-render. Use one to reach a DOM node, and one to keep a value the screen does not show, such as a timer id. In React 19 a function component takes ref as an ordinary prop; forwardRef is no longer needed.

What to notice

  • Rule: do not read or write ref.current during render, only in handlers and effects. Render must be a pure function of props and state.
  • useEffect(() => stop, []) returns stop as the cleanup. It reads the ref, so it always sees the current timer id.

Example: React 19 hooks

Hooks

React 19 added hooks for async work. All of these are exported by the installed react 19.3:

APIUse it forOn this page
useActionState(fn, initial)a form whose submit runs an async function; gives result state and isPendingbelow
use(promise) / use(context)read a promise inside Suspense; read context, even inside an ifbelow
useTransitionmark a slow update as interruptible; accepts async functions in 19habits
useOptimisticshow the expected result while a request runs, roll back on failureproject 19
ref as a propno more forwardRefuseRef twice
<Context value>render a context directly as its providerexercise 13
useFormStatus (react-dom)a submit button that knows its form is pending
useEffectEvent, <Activity> (19.2+)read latest props in an effect without re-running it; hide UI but keep its state

useActionState wires a form to an async function. The function gets the previous state and the FormData, and returns the next state:

use reads a promise. The component suspends until it settles, and the nearest Suspense shows its fallback meanwhile:

What to notice

  • After a successful form action React resets uncontrolled inputs, which is why the amount box is empty again. Controlled inputs keep their state.
  • use(promise) with a promise created during render loops forever: each render makes a new promise, which suspends again.
  • Testing trap: a plain render of a suspending component stays on the fallback and React warns "the act call was not awaited". Wrap it in await act(async () => ...).

9. useFetch with abort

Hooks · medium, write the hook and its test

The Essentials useFetch has no error state, no abort and a race. Write useFetch<T>(url) that returns one of { status: "loading" }, { status: "error", error } or { status: "success", data }. Then write its test with renderHook and a stubbed fetch.

  • Loading first, then success with the parsed JSON.
  • A non-2xx response gives { status: "error", error: "HTTP 404" }.
  • Unmounting aborts the request (the signal passed to fetch is aborted).
  • Changing the URL shows loading again and never shows data from the old URL.

Hints

  • Tag the stored result with the URL it belongs to, as in exercise 6.
  • The mock's call arguments are in fetchMock.mock.calls. A promise that never settles (new Promise(() => {})) keeps the hook loading.
  • waitFor(() => expect(...)) retries an assertion until it passes.
Solution
  • Returning { status: "loading" } when the URL differs avoids calling setState at the start of the effect, which would cost an extra render.
  • In a real app this hook grows caching, retries and refetch on focus. That is TanStack Query; write this once to know what it does for you.

10. Account with useReducer

Hooks · medium

Write accountReducer and an AccountCard that uses it. The actions are a discriminated union: deposit and withdraw carry an amount, reset carries nothing. The state is { balance, error } and starts at { balance: 0, error: null }.

  • Deposit 1000, withdraw 300: balance ₹700, no error.
  • Withdrawing more than the balance leaves it unchanged and sets "Insufficient funds".
  • Any successful action clears the error; reset returns to the start state.
  • The card shows the owner, "Balance: ₹...", an "Amount" input and Deposit, Withdraw, Reset buttons. Deposit and Withdraw are disabled until the amount is above 0.

Hints

  • Inside case "deposit": TypeScript knows action.amount exists; inside case "reset": it does not.
  • Assigning action to a variable of type never in the default branch turns a forgotten case into a compile error.
Solution
  • actions.reduce(accountReducer, initialState) works because a React reducer has exactly the signature Array.reduce expects. That is the whole idea, and it makes reducers trivial to unit test.

11. What re-renders?

Hooks · hard, predict the output, then fix

Row is wrapped in memo and counts its renders. After the first render the counter is reset to 0. Answer two questions: (a) you type one character into "Note": how many Row renders? (b) you then click the first owner: how many?

Hints

  • memo skips a render only if every prop is Object.is-equal to last time.
  • Which prop is a new value on every render of the parent?
Solution

(a) 5 and (b) 5: every row, every time. onSelect={(id) => setSelectedId(id)} creates a new function on each parent render, so memo always sees a changed prop and never skips.

Pass a stable function. The state setter already is one; for a callback with logic, wrap it in useCallback:

Re-run the counter after the fix: typing renders 0 rows; clicking the first owner renders 1 (its selected went from false to true); clicking a second owner then renders 2 (the old and the new selection).

ToolKeeps stableWorth it when
memo(Component)skips a child's render when props are equalthe child is slow or there are many of it
useCallback(fn, deps)a function's identityit is passed to a memo child or used in effect deps
useMemo(() => v, deps)a computed value (or an object/array identity)the computation is measurably slow, or the value goes to a memo child
  • Other memo-breakers: style={{ ... }}, items={list.filter(...)}, options={{ ... }}. Any object literal in JSX is new each render.
  • Without memo, a child re-renders whenever its parent does, whatever its props. useCallback on its own does nothing for rendering.
  • The React Compiler, if a project enables it, inserts this memoisation automatically. It is not part of the Vite template.

Composition

Part 5 of 8 · building components out of components

React has no inheritance between components. Reuse comes from passing JSX in (children, slots), passing functions in (render props), and sharing state through context.

Example: children, slots and render props

Composition

Panel takes JSX through children and a named slot (actions). DataList is generic: it owns the list markup and the empty state, and the caller says how one item looks through a function prop.

What to notice

  • TypeScript infers T = Account from items, so a in renderItem is typed without annotations.

Example: error boundary and lazy loading

Composition

An error boundary catches errors thrown while rendering its children and shows a fallback instead of a blank page. It is the one thing that still needs a class component. lazy splits a component into its own JavaScript file that loads on first render, and Suspense shows a fallback while it loads.

Error thrown inCaught by a boundary?
render, or a child's renderyes
a lazy import that fails (network)yes
an event handlerno: use try/catch and state
a setTimeout or promise callbackno, unless you rethrow it during render (store it in state, then throw)
  • To let the user retry, give the boundary a key that changes (for example the route path): a new key mounts a fresh boundary with no error.

12. Stop the prop drilling

Composition · easy

Here user travels through Header and Menu, which never use it, to reach Avatar. Replace the drilling with a UserProvider and a useCurrentUser() hook.

  • Header, Menu and Avatar take no props.
  • Inside <UserProvider user={{ name: "Rishikesh Agrawani" }}>, the avatar shows "RA" with the label "Signed in as Rishikesh Agrawani".
  • Calling useCurrentUser() outside the provider throws "useCurrentUser must be used inside UserProvider".

Hints

  • Create the context with null as default; the hook checks for null and throws. Then the return type has no null in it.
  • In React 19 you can render <UserContext value={...}> directly; .Provider still works.
Solution
  • Every component that reads a context re-renders when its value changes. Pass a stable value (a state variable, or useMemo for an object) and split rarely-changing from often-changing data into separate contexts.
  • Drilling through two levels is fine. Reach for context when many distant components need the same thing, or try passing JSX as children first: the middle components then never see the data.

13. Compound Tabs

Composition · medium

Build a Tabs family used like this. The parts share the active tab through a context private to the file, so the caller never passes it around.

  • Tabs render with role="tab" inside a role="tablist"; the active one has aria-selected="true".
  • Only the active panel is rendered, with role="tabpanel", labelled by its tab.
  • Clicking "Transactions" shows "No transactions yet".

Hints

  • Object.assign(TabsRoot, { List, Tab, Panel }) attaches the parts with correct types.
  • useId() in the root gives a prefix for the id / aria-controls / aria-labelledby pairs.
Solution
  • This is how headless UI libraries (Radix, React Aria, Headless UI) are built: state in a context, markup and ARIA in small parts, styling left to you.

Routing

Part 6 of 8 · react-router-dom 7

React Router 7 ships everything from the react-router package; react-router-dom re-exports it, so either import works. Every example exports its routes separately from the BrowserRouter, so tests can wrap them in a MemoryRouter that starts at any URL.

Example: nested routes

Routing

The accounts section has its own layout (a list on the left) with an Outlet for the detail on the right. An index route fills the outlet when no account is chosen, and an unknown account id gets its own message, separate from the site-wide not-found route.

What to notice

  • Child paths are relative ("accounts", ":accountId"), and so is <Link to="3">: it resolves against the route it is rendered in.
  • useParams values are always strings (or undefined). Convert and validate them, as you would a path parameter in a backend handler.
  • NavLink adds the active class (and aria-current="page") when its route matches; /accounts is active for /accounts/3 too.

14. Filter in the URL

Routing · medium

Write AccountFilter: an "Owner" text input and a "Minimum balance" select (Any, ₹1,000, ₹10,000) that filter the accounts. The filter lives in the URL (?owner=sa&min=1000) instead of state, so it survives a refresh and can be shared as a link.

  • Opening /?owner=sub shows only Subhash Agrawani, with "sub" already in the input.
  • Typing updates the URL; empty values are removed from it rather than left as owner=.
  • Changing one filter keeps the other.
  • Typing does not add a browser history entry per keystroke.

Hints

  • const [params, setParams] = useSearchParams(). params.get("owner") is string | null.
  • setParams accepts an updater (prev => next) and options such as { replace: true }.
  • To check the URL in a test, render a tiny component next to the one under test that prints useLocation().search.
Solution
  • URL state is the right home for anything a user would bookmark or share: filters, sort, page, selected tab. It is also free "lifting": any component can read it.
  • replace: true overwrites the current history entry. Without it, Back would step through every keystroke.

15. Protected route

Routing · medium

The Essentials ProtectedRoute sends a signed-out user to /login, but after signing in they land on the home page and lose where they were going. Build the version that brings them back, with a fake signIn(name) instead of a real API.

  • Signed out, opening /accounts?tab=2 shows the "Sign in" page.
  • Clicking "Sign in as Rishikesh Agrawani" goes to /accounts?tab=2 (search included), which shows "Accounts of Rishikesh Agrawani".
  • "Sign out" on that page goes back to "Sign in".
  • The login page is not left in history: Back from /accounts does not return to it.

Hints

  • <Navigate to="/login" replace state={{ from: ... }} /> carries the original location; useLocation().state reads it on the login page.
  • useLocation().state is typed any; give it a type before use.
Solution
  • signIn and navigate in one handler are batched, so RequireAuth already sees the user when /accounts renders.
  • Both redirects use replace, so history holds /accounts once and never /login.

Testing and habits

Part 7 of 8 · Testing Library, refactoring, rules of thumb

Every test on this page follows one idea from Testing Library: test what the user sees and does (roles, labels, text, clicks), not component internals.

Example: testing toolbox

Testing and habits

NeedUseSeen in
find an elementgetByRole(role, { name }) first, then getByLabelText, getByText; getByTestId lasteverywhere
assert something is absentqueryBy... (returns null instead of throwing)5
wait for something to appearawait findBy..., or await waitFor(() => expect(...))fetch, 9
act like a useruserEvent.type / click / selectOptions / keyboard (await each)everywhere
replace fetchvi.stubGlobal("fetch", vi.fn(...)) + vi.unstubAllGlobals()6, 8
replace a modulevi.mock("./api", () => ({ ... })) + vi.mocked(fn)below
control timevi.useFakeTimers() + act(() => vi.advanceTimersByTime(ms))7
test a hook alonerenderHook(() => useX()), result.current, rerenderhooks
start at a URL<MemoryRouter initialEntries={["/path"]}>routes

When a component calls an API module, mock the module instead of fetch. The test then states the contract ("calls closeAccount(4)") rather than URL details:

What to notice

  • vi.mock is hoisted, so the component imports the mock even though the call appears after the imports.
  • Querying by role and name doubles as an accessibility check: if the test cannot find "Close account" as a button, neither can a screen reader.

16. Write the test

Testing and habits · medium, write the test

The component below works. Write src/DepositForm.test.tsx so that it would catch a regression in any of the four behaviours listed. Only use what a user can see and do.

  • Submitting an empty box shows "Enter a whole amount above 0" and does not call onDeposit.
  • "12.5" is rejected the same way.
  • "500" calls onDeposit(500) once, clears the box and removes the error.
  • Pressing Enter in the box submits, like clicking the button.

Hints

  • vi.fn() records calls; toHaveBeenCalledExactlyOnceWith(500) checks count and arguments in one go.
  • userEvent.type(input, "500{Enter}") types and presses Enter.
  • Write a small setup() function that renders and returns the input and the mock; it keeps each test to a few lines.
Solution
  • Each test checks one behaviour and is named after it, so a failure message reads like a bug report.
  • The third test submits a bad value first; otherwise "removes the error" passes even if the code never removes it.

17. Six problems, one component

Testing and habits · hard, spot the bugs

This component "mostly works". Find six problems (bugs, wasted renders, accessibility), then rewrite it. The owner of an account is matched by the full name typed in two inputs.

  • The rewritten version shows "Total: ₹3,500" for Sandhya's two accounts (₹2,500 and ₹1,000), then "Total: ₹2,500" after hiding account 6.
  • With a name that owns nothing, no total line and no stray characters appear.

Hints

  • Two of the six are "state that should not exist". One is "state that never changes reference".
  • Look at the total: whose accounts does it add up?
Solution
#ProblemFix
1fullName is duplicated state synced by an effect: an extra render and one frame of the old namederive it: `${first} ${last}`
2total is duplicated state, and it sums all accounts, not the owner'sderive it from mine
3hidden.push mutates state and passes the same array back, so React skips the render: Hide does nothingsetHiddenIds((ids) => [...ids, id])
4mine.length && renders "0" when the list is emptymine.length > 0 &&
5index keys on a list whose items are removedkey={a.id}
6inputs without labels, and several identical "Hide" buttonswrap in <label>; give each button an aria-label
  • The rewrite has three pieces of state where the original had five, and no effects. Fewer states, fewer ways to disagree.

Performance and correctness habits

Testing and habits

Rules of thumb that cover most real-world React performance work. Measure with the React DevTools Profiler before optimising.

HabitWhy
Store the minimum state; derive the rest during renderno sync effects, no stale copies (example)
Keep state as low as possiblea keystroke re-renders only the component that owns the input, not the page
Split components along what changesa big component with one fast-changing input re-renders everything in it; move the input and its state into a child
Stable, unique keys from the datacorrect state per row, minimal DOM work (exercise 4)
Never mutate stateReact and memo compare by reference (example)
memo / useCallback only where the Profiler shows a costthey add code and comparisons; most renders are cheap (exercise 11)
Virtualise long lists (thousands of rows)render only the visible rows; use a library such as TanStack Virtual or react-window rather than writing it
lazy for big routes and rarely used screenssmaller first download (example)
useTransition / useDeferredValue for slow updates driven by typinginput stays responsive (example)
Every effect that starts something stops it in cleanupno leaks, no races, Strict Mode stays quiet (example)

Mini projects

Part 8 of 8 · three small bank apps that combine the parts

Each project is a few files in its own folder under src/. Give yourself an hour or two for each, write the test file first from the behaviour list if you like, and compare at the end.

18. Accounts dashboard

Mini projects · project

A dashboard over a list of accounts: a table with filter and sort, a total, and a deposit form. The accounts live in a useReducer store shared through context, so the form and the table never pass data to each other.

  • <BankProvider initial={accounts}> holds the accounts; useBank() returns { state, dispatch } and throws outside the provider.
  • The reducer handles deposit and withdraw (each with accountId and amount); overdrawing sets "Insufficient funds" and changes nothing.
  • An "Owner" select ("All owners" plus each distinct owner) filters the rows; a "Sort by" select orders by owner name or by balance, highest first.
  • The table footer says "Total of N: ₹..." for the visible rows.
  • The deposit form has an "Account" select, an "Amount" input and a "Deposit" button; a bad amount shows "Enter a whole amount above 0".

Hints

  • Filtered, sorted and totalled rows are all derived during render. The only state besides the store is the two select values.
  • [...new Set(list.map((a) => a.owner))] gives the distinct owners.
Solution
  • The store file holds the only rules (the reducer); the components only read and dispatch. Swapping the reducer for API calls later touches one file.
  • A row's accessible name is its text, so getByRole("row", { name: /Malinikesh/ }) finds a table row by its content.

19. Transfer with rollback

Mini projects · project

A transfer form that moves money between two accounts. The balances change on screen the moment you press Transfer (optimistic update), and go back if the bank declines. The bank is a function passed as a prop, so tests decide when it answers and whether it fails.

  • The balances list shows "Owner: ₹..." per account; the form has "From" and "To" selects, an "Amount" input and a "Transfer" button.
  • Validation before sending: two different accounts, a whole amount above 0, and no more than the source balance ("Insufficient funds"). Invalid transfers are never sent.
  • While sending, the new balances are already shown and the button reads "Sending..." and is disabled.
  • On success the message is "Transfer complete" and the balances stay; on failure the message starts "Transfer failed:" and the balances return to what they were.

Hints

  • const [shown, addOptimistic] = useOptimistic(accounts, applyTransfer). Call addOptimistic inside a transition; when the transition ends, shown falls back to the real accounts.
  • So rollback is free: on failure, just do not update accounts.
  • State updates after an await inside startTransition need their own startTransition to count as part of it.
Solution
  • Validation runs against shown, the optimistic balances, so a second transfer while the first is pending cannot overdraw.
  • Injecting send as a prop (with a real default) is dependency injection, the same move as passing a repository into a service in backend code. The test needs no vi.mock.

20. Transactions table

Mini projects · project

A searchable, paginated table of 23 transactions, five per page, where the search text and the page number live in the URL (?q=hem&page=2). Use the data file below as given.

  • A search box ("Search transactions") matches owner or kind, case-insensitively. A new search goes back to page 1 and does not add history entries.
  • Previous / Next buttons change page in the URL (these do add history entries, so Back works), and are disabled at the ends. The text reads "Page N of M".
  • Opening a URL with a page that is too large, zero or not a number shows the nearest valid page.
  • No matches shows "No transactions match" and "Page 1 of 1".

Hints

  • Read q and page from useSearchParams and compute everything else: matches, page count, clamped page, the slice of rows.
  • Number(params.get("page")) || 1 turns null, "" and "abc" into 1.
Solution
  • The page number is never stored in state: it is read from the URL and clamped during render, so a hand-edited URL cannot break the table.
  • With a real API the same component sends q and page to the server (as query parameters) and the server does the slicing; the URL handling does not change.

Where to go next

Mini projects

Everything on this page runs in the browser: the app fetches JSON from an API you write elsewhere. Next.js adds the server side to the same components, with file-based routing, data loading on the server and server actions instead of hand-written fetch calls.

  • Next.js Essentials: the concepts, in the same style as React Essentials.
  • Next.js practice: usage examples and exercises for the Next.js side, built the same way as this page.

Back to React Essentials or all tutorials.