Thuta Learning
React
ExercisesWeb DevelopmentIntermediate

Practice: Hooks & Data

ReactLesson 3350 min

What you'll walk away with

  • Write a separate async function inside useEffect and manage fetching with loading, error and data states
  • Check res.ok and discard stale responses with an ignore-flag cleanup
  • Use createContext, a Provider and useContext to reach a component two levels down without props
  • Explain that a custom hook shares logic, not state, and that useParams returns strings

Explain it simply

Explain it simply

This practice is a step harder than the Core Concepts one. It combines what you learned in the Intermediate and Advanced chapters: useEffect, useContext, custom hooks, data fetching and React Router. These are patterns you will meet almost daily in real apps.

There are four tasks. Task 1 shows a user list from an API with a loading state. Task 2 sends a light/dark theme two levels down with Context. Task 3 writes a useToggle hook for things like opening a modal or showing a sidebar. Task 4 reads the id from a /users/:id route and displays it. Try each one yourself before reading the solutions.

Problem → Why → Solution

The problem: a fetch that only works on the happy path

Most first attempts at Task 1 look like this. With good Wi-Fi and a working API the user list appears, so it feels finished. But the console already shows a warning that an effect must not return anything except a cleanup function.

Mistype the URL as /userz and the server answers 404 with {}, and fetch does not throw. setUsers({}) runs and the app crashes with users.map is not a function. With no network at all, fetch rejects, setLoading(false) is never reached, and "Loading..." stays on screen forever.

UserList.jsx (first try)
useEffect(async () => {
  // an async callback returns a Promise, but React expects a cleanup function
  const res = await fetch("https://jsonplaceholder.typicode.com/users");
  setUsers(await res.json()); // a 404 body like {} is stored too
  setLoading(false);          // never reached if fetch rejects
}, []);

What is going wrong?

An async function always returns a Promise, while React expects an effect to return either undefined or a cleanup function. fetch rejects only on network failure and resolves normally for 404 or 500, so you must check res.ok yourself. And you need finally to switch loading off whether or not an error happened.

Core concept: four hooks, four traps

Each task exercises one hook, and each hook has one trap that catches people who have not met it before. Check your own code against these four points.

1. Fetching inside an effect (Task 1)

Keep the effect callback a plain function, declare async function loadUsers inside it and call it right away. Check res.ok inside try, store the error in catch, and turn loading off in finally. With [] as dependencies it runs after mount; StrictMode runs effects twice in development, and the ignore-flag cleanup makes that safe too.

2. Skipping levels with Context (Task 2)

createContext("light") creates a context with a default value. The Provider hands its value to the whole tree beneath it, and useContext reads the value of the nearest Provider above. Toolbar in the middle never touches a theme prop. Rendered outside any Provider, a component gets the default "light".

3. A custom hook shares logic (Task 3)

useToggle is a function that wraps useState. Sidebar and FaqItem call the same hook, but every call creates its own state, so toggling one never affects the other. To truly share state you need Context or to lift the state into a parent.

4. URL params are strings (Task 4)

With :id in the route, destructure the same name, { id }, from useParams(). At /users/3, id is the string "3", not the number 3, so convert and validate it before comparing it with numeric ids in your data.

Here is the first point made visible in Node. Whatever an effect callback returns, React keeps as its cleanup. An async callback returns a Promise even when you never write return.

effect-return-value.js
// What an effect callback returns is what React treats as the cleanup.
const asyncEffect = async () => {
  /* await fetch(...) */
};
const plainEffect = () => {
  let ignore = false;
  return () => {
    ignore = true;
  };
};

const fromAsync = asyncEffect();
const fromPlain = plainEffect();
console.log("async callback returns a Promise:", fromAsync instanceof Promise);
console.log("plain callback returns a function:", typeof fromPlain === "function");

// async callback returns a Promise: true
// plain callback returns a function: true
Mental model: each hook answers one question
  1. useEffect: what to sync after render
  2. useContext: what did a parent provide
  3. Custom hook: where to reuse this logic
  4. useParams: what does the URL say

When unsure which hook you need, first ask which of these four questions you are trying to answer.

General pattern

jsx
useEffect(() => {
  let ignore = false;
  async function load() {
    try { const data = await getData(); if (!ignore) setData(data); }
    catch (err) { if (!ignore) setError(err); }
    finally { if (!ignore) setLoading(false); }
  }
  load();
  return () => { ignore = true; };
}, [dependency]);

const value = useContext(SomeContext); // nearest Provider's value

Declare and call an async function inside the effect, set the three states with try/catch/finally, and let the cleanup raise the ignore flag. Reading a context value is a single useContext line.

Worked solutions: Tasks 1 to 4

Compare only after writing your own. The files are separated by comments. Task 4 needs react-router-dom installed and the app wrapped in <BrowserRouter>. Task 1 already includes the error state, which answers the task's five-minute extension.

src (4 tasks)
// Task 1 - src/components/UserList.jsx
import { useEffect, useState } from "react";

function UserList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    let ignore = false;

    async function loadUsers() {
      try {
        const res = await fetch("https://jsonplaceholder.typicode.com/users");
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        const data = await res.json();
        if (!ignore) setUsers(data);
      } catch (err) {
        if (!ignore) setError(err.message);
      } finally {
        if (!ignore) setLoading(false);
      }
    }

    loadUsers();
    return () => {
      ignore = true;
    };
  }, []);

  if (loading) return <p>Loading...</p>;
  if (error) return <p role="alert">Could not load users: {error}</p>;
  return (
    <ul>
      {users.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

export default UserList;

// Task 2 - src/theme.jsx
import { createContext, useContext, useState } from "react";

const ThemeContext = createContext("light");

function ThemeBadge() {
  const theme = useContext(ThemeContext);
  return <span className={`badge badge-${theme}`}>Theme: {theme}</span>;
}

function Toolbar() {
  return (
    <div className="toolbar">
      <ThemeBadge />
    </div>
  );
}

export function ThemeApp() {
  const [theme, setTheme] = useState("light");
  const nextTheme = theme === "light" ? "dark" : "light";

  return (
    <ThemeContext.Provider value={theme}>
      <button type="button" onClick={() => setTheme(nextTheme)}>
        Switch to {nextTheme}
      </button>
      <Toolbar />
    </ThemeContext.Provider>
  );
}

// Task 3 - src/hooks/useToggle.js
import { useState } from "react";

function useToggle(initialValue = false) {
  const [value, setValue] = useState(initialValue);
  const toggle = () => setValue((v) => !v);
  return [value, toggle];
}

export default useToggle;

// Task 3 usage - two components, two independent states
function Sidebar() {
  const [open, toggleOpen] = useToggle(true);
  return (
    <aside>
      <button type="button" onClick={toggleOpen}>{open ? "Hide" : "Show"} menu</button>
      {open && <nav>Menu links</nav>}
    </aside>
  );
}

function FaqItem() {
  const [expanded, toggleExpanded] = useToggle();
  return (
    <div>
      <button type="button" aria-expanded={expanded} onClick={toggleExpanded}>
        What is a hook?
      </button>
      {expanded && <p>A function that starts with use.</p>}
    </div>
  );
}

// Task 4 - src/components/UserDetail.jsx
// route: <Route path="/users/:id" element={<UserDetail />} />
import { useParams } from "react-router-dom";

function UserDetail() {
  const { id } = useParams();
  return <h3>User Detail: {id}</h3>;
}

export default UserDetail;

Code breakdown

  1. Ignore flag for stale responseslet ignore = false;

    Each run of the effect gets its own flag. Once the cleanup sets it to true, a response that arrives later no longer touches state.

  2. HTTP errors become real errorsif (!res.ok) throw new Error(`HTTP ${res.status}`);

    fetch does not treat 404 or 500 as failures, so the code throws itself and lands in the catch block.

  3. Loading always endsif (!ignore) setLoading(false);

    Sitting in finally, it removes "Loading..." after success and after an error alike.

  4. Reading the nearest Providerconst theme = useContext(ThemeContext);

    ThemeBadge sits inside Toolbar yet reads ThemeApp's Provider value directly, without a prop, and re-renders when the theme changes.

  5. Hook returns a value and an actionreturn [value, toggle];

    Returning an array like useState does lets each caller choose names such as [open, toggleOpen] or [expanded, toggleExpanded].

  6. Param name matches the routeconst { id } = useParams();

    The name must match :id in the route to get a value, and that value is a string.

You should see
UserList shows "Loading..." first and then the list of user names; if the request fails it shows "Could not load users: ...". The theme badge starts at "Theme: light" and flips between dark and light on every click, the Sidebar and the FAQ item open and close independently, and /users/3 shows "User Detail: 3".

What the ignore flag protects against

In Task 1 the dependency list is [], so a race is unlikely. But in an effect with a dependency such as [userId], switching quickly from user 1 to user 2 starts two competing requests. If the first one is slower and arrives last, the screen ends up showing user 1. React runs the old effect's cleanup before the new effect, so the ignore flag throws the stale response away.

The code below models that race with setTimeout.

race-model.mjs
// Two requests for different users; the first one is slower and finishes last.
const delay = (ms, value) =>
  new Promise((resolve) => setTimeout(() => resolve(value), ms));
const fakeFetchUser = (id) => delay(id === 1 ? 30 : 10, { id, name: `User ${id}` });

async function run(useIgnoreFlag) {
  let shown = "(nothing yet)";
  let cleanupPrevious = () => {};

  for (const id of [1, 2]) {
    cleanupPrevious(); // React runs the old effect's cleanup before the next one
    let ignore = false;
    fakeFetchUser(id).then((user) => {
      if (!useIgnoreFlag || !ignore) shown = user.name;
    });
    cleanupPrevious = () => {
      ignore = true;
    };
  }

  await delay(50);
  console.log(useIgnoreFlag ? "with ignore flag:   " : "without ignore flag:", shown);
}

await run(false);
await run(true);

// without ignore flag: User 1
// with ignore flag:    User 2

Two ways to write the Provider

This tutorial uses <ThemeContext.Provider value={theme}>. React 19 also accepts the shorter <ThemeContext value={theme}>. Check your project's React version and use one form consistently.

In real projects

In real projects

These four tasks are the skeleton of a real app. A product list page fetches data, and a product detail page reads its id from /products/:id. Values the whole app needs, such as the theme, the logged-in user or the chosen language, travel through Context, while modals, dropdowns and accordions share small hooks like useToggle.

In production, teams usually do not hand-write fetch-in-effect; they use a library such as TanStack Query or SWR, or their framework's data loading (React Router loaders, Next.js Server Components), which provide caching, retries and race handling. The ideas underneath those tools are the same ones you practised: three states for loading, error and data, checking res.ok, and discarding stale responses.

Common mistakes

Common mistakes

Writing useEffect(async () => ...)

The callback returns a Promise, React warns in the console, and you can no longer return a cleanup function. Declare a separate async function inside the effect, call it, and return the cleanup from the effect itself.

Expecting a custom hook to share state

If a Header and a Sidebar both call useToggle(), people expect opening one to open the other. It does not, because every hook call gets its own state. To share one state, lift it to a common parent or provide it through Context.

Comparing a URL param directly with a number

users.find((u) => u.id === id) returns undefined because the string "3" never equals the number 3, so the page always says "User not found". Convert with Number(id) and reject invalid values such as "abc".

Best practices

Making this practice count

  • Switch the DevTools Network tab to Offline and to a slow profile, and watch Task 1's loading and error states yourself
  • Break the URL on purpose and check that a 404 shows an error message instead of crashing
  • Render ThemeBadge once outside the Provider so you see the default value with your own eyes
  • Open /users/abc and decide what the page should show for an invalid id

Mini challenge

Pull the fetch logic out so you can test it

Move the logic of Tasks 1 and 4 out of the components. loadUsers(fetchImpl, url) takes the fetch function as an argument, so you can test success, a 404 and an offline failure in Node with fake fetch functions and no network. parseUserId(param) validates the string from useParams and turns it into a number.

  • loadUsers always resolves to a { status, users, error } object and never throws
  • When res.ok is false, report it as an "HTTP <status>" error
  • When fetchImpl rejects, use err.message as the error
  • parseUserId returns a number for positive integer strings like "3" and null for "abc", "-1", "0" and undefined
users-logic.mjs
async function loadUsers(fetchImpl, url) {
  // TODO: call fetchImpl(url); throw on !res.ok; parse JSON
  // TODO: return { status: "success", users, error: null }
  // TODO: on any error return { status: "error", users: [], error: message }
}

function parseUserId(param) {
  // TODO: accept only digit strings, convert with Number, reject 0
}

// TODO: three fake fetch functions: one ok, one 404, one that rejects
// TODO: print the result of loadUsers for each, then parseUserId for
//       "3", "007", "abc", "-1", "0" and undefined

Expected: The ok case prints success with two user names, the 404 case "HTTP 404" and the offline case "Failed to fetch". parseUserId gives 3 for "3", 7 for "007" and null for everything else.

Show hint

A fake fetch only has to return an object shaped like { ok, status, json: async () => data }. For the offline case write async () => { throw new Error("Failed to fetch"); }. /^\d+$/ checks for digits only. In the component, call const result = await loadUsers(fetch, url) and set the three states from it.

Show solution
users-logic.mjs
async function loadUsers(fetchImpl, url) {
  try {
    const res = await fetchImpl(url);
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const users = await res.json();
    return { status: "success", users, error: null };
  } catch (err) {
    return { status: "error", users: [], error: err.message };
  }
}

function parseUserId(param) {
  if (!/^\d+$/.test(param ?? "")) return null;
  const id = Number(param);
  return id > 0 ? id : null;
}

const okFetch = async () => ({
  ok: true,
  status: 200,
  json: async () => [
    { id: 1, name: "Aung Aung" },
    { id: 2, name: "Su Su" },
  ],
});
const notFoundFetch = async () => ({ ok: false, status: 404, json: async () => ({}) });
const offlineFetch = async () => {
  throw new Error("Failed to fetch");
};

const url = "https://example.com/users";
const cases = [["ok", okFetch], ["404", notFoundFetch], ["offline", offlineFetch]];
for (const [label, impl] of cases) {
  const result = await loadUsers(impl, url);
  const names = result.users.map((user) => user.name).join(", ") || "-";
  const error = result.error ?? "-";
  console.log(`${label}: ${result.status} | users: ${names} | error: ${error}`);
}

for (const param of ["3", "007", "abc", "-1", "0", undefined]) {
  const shown = param === undefined ? "undefined" : JSON.stringify(param);
  console.log(`useParams id ${shown} -> ${parseUserId(param)}`);
}

Quick quiz 1 / 3

Sidebar and FaqItem both call useToggle(). What happens to FaqItem when you click Sidebar's button?

Quick quiz 2 / 3

The route is /users/:id and the URL is /users/3. After const { id } = useParams();, what does users.find((u) => u.id === id) return when every u.id is a number?

Quick quiz 3 / 3

With const ThemeContext = createContext("light");, what does ThemeBadge show when rendered outside any Provider?

What to remember

  • Never make the effect callback async; declare an async function inside, call it, and return a cleanup
  • Check res.ok, store errors in catch, end loading in finally, and drop stale responses with an ignore flag
  • Context delivers a value to every component under its Provider without props, and falls back to the default without one
  • A custom hook shares logic, not state; useParams returns strings, so convert and validate them

React Documentation — React

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Practice: Hooks & Data | Thuta Learning