Skip to content

Component Lifecycle and Effects in React

In Lesson 15, our custom hook saved a selection whenever we called its update function. Now we’ll explore how React can synchronize an external system with state after a render is committed.

We’ll use that idea twice: keep browser storage synchronized with the selected resource, and load resource data from our backend. Both involve work outside the calculation of JSX. React calls this kind of synchronization an Effect.

At the end of this class, you should be able to…

  • Distinguish rendering, committing UI updates, and running Effects.
  • Use useEffect to synchronize state with an external system.
  • Explain dependency arrays and the cleanup function.
  • Fetch resource data through a custom hook with loading, error, and retry states.
  • Prevent an obsolete request from overwriting a newer request’s state.

useEffect() lets us keep a component synchronized with something outside React, such as browser storage or a server. React may render a component repeatedly, so rendering should only calculate the UI. The Effect’s callback runs after React commits the update, keeping storage writes and requests out of that calculation.

Use an Effect when the work should follow the component appearing or a dependency changing. Here, storage follows selectedResource; fetching starts when the component using our hook mounts and repeats when requestVersion changes for a retry.

We don’t need an Effect to filter resources from existing state; we can calculate that during rendering. Work caused by one action, such as submitting a form, belongs in that event handler. Being asynchronous doesn’t, by itself, mean that fetch() needs an Effect.

React calls our component to calculate the UI: render. It applies the necessary DOM changes: commit. An Effect then performs its synchronization work. When dependencies change, React runs the previous cleanup before the next setup. Cleanup also runs when the component is removed.

Dependency argument When setup runs
Omitted After every commit for the component
[] On mounting, with no dependency-driven reruns
[selectedResource] On mounting and after that value changes

Dependencies must include the reactive values used by the Effect. They aren’t an arbitrary schedule to choose for convenience. React’s useEffect reference describes setup, dependencies, and cleanup.


From the root of your workbook, grab today’s starter for your section, or continue with the copy you already have.

Terminal window
pnpm dlx tiged --disable-cache --force DG-InClass/SDEV-2150-A01-Sep-2026/sk/day-16/example/lesson-16-starter ./src/lesson-16

Use two terminals, each starting at your workbook root.

Terminal 1: frontend
cd src/lesson-16/frontend
pnpm install
pnpm dev
Terminal 2: backend
cd src/lesson-16/backend
pnpm install
pnpm start

Open the frontend URL printed by Vite. In another browser tab, check the resource endpoint. You should see an array of resource objects. Keep the backend running while we work.

Paths below start inside src/lesson-16/frontend. The starter already calls useSelectedResource in App, but Results still imports hard-coded data. We’ll finish the storage refactor before introducing the network request.

  1. Keep the storage read in the initializer.

    Open src/hooks/useSelectedResource.js. Its initializer already reads JSON. Move storage access into the try block as well, so unavailable storage and malformed JSON both fall back to no selection.

    src/hooks/useSelectedResource.js
    import { useState } from 'react';
    import { useEffect, useState } from 'react';
    src/hooks/useSelectedResource.js
    const [selectedResource, setSelectedResource] = useState(() => {
    const stored = sessionStorage.getItem(STORAGE_KEY);
    if (stored) {
    try {
    return JSON.parse(stored);
    } catch {
    return null;
    }
    try {
    const stored = sessionStorage.getItem(STORAGE_KEY);
    if (stored === null) return null;
    const resource = JSON.parse(stored);
    return resource && typeof resource.id === 'string'
    && typeof resource.title === 'string' ? resource : null;
    } catch {
    return null;
    }
    return null;
    });

    If you brought forward the guarded initializer from Lesson 15, keep it. This edit brings the supplied starter to the same point.

  2. Synchronize storage with an Effect.

    Replace the wrapper function with an Effect, and return React’s setter directly.

    src/hooks/useSelectedResource.js
    function updateSelectedResource(resource) {
    setSelectedResource(resource);
    if (resource === null) {
    sessionStorage.removeItem(STORAGE_KEY);
    } else {
    sessionStorage.setItem(STORAGE_KEY, JSON.stringify(resource));
    useEffect(() => {
    try {
    if (selectedResource === null) {
    sessionStorage.removeItem(STORAGE_KEY);
    } else {
    sessionStorage.setItem(STORAGE_KEY, JSON.stringify(selectedResource));
    }
    } catch (error) {
    console.warn('Selection could not be saved for this tab.', error);
    }
    }
    }, [selectedResource]);
    return [selectedResource, updateSelectedResource];
    return [selectedResource, setSelectedResource];

    If you’re continuing your Lesson 15 implementation, remove its entire wrapper, including its try/catch, when making this replacement.

    Select a resource and refresh. The same selection should return. App’s hook call and component props haven’t changed.

    This Effect doesn’t need cleanup: writing a stored value doesn’t leave a timer, subscription, or request running. Don’t remove the stored key in cleanup; that would undo the persistence we’re trying to achieve.

  3. Create a hook for loading resources.

    Add src/hooks/useResources.js. Read the request from top to bottom before using the hook.

    src/hooks/useResources.js
    import { useEffect, useState } from 'react';
    const API_BASE_URL = 'http://localhost:3000';
    export function useResources() {
    const [resources, setResources] = useState([]);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState(null);
    const [requestVersion, setRequestVersion] = useState(0);
    useEffect(() => {
    const controller = new AbortController();
    const { signal } = controller;
    async function fetchResources() {
    try {
    const response = await fetch(`${API_BASE_URL}/resources`, { signal });
    if (!response.ok) {
    throw new Error(`Request failed: ${response.status} ${response.statusText}`);
    }
    const data = await response.json();
    if (!Array.isArray(data)) {
    throw new Error('Expected an array of resources.');
    }
    if (!signal.aborted) setResources(data);
    } catch (err) {
    if (!signal.aborted) setError(err);
    } finally {
    if (!signal.aborted) setIsLoading(false);
    }
    }
    fetchResources();
    return () => controller.abort();
    }, [requestVersion]);
    function refetch() {
    setIsLoading(true);
    setError(null);
    setRequestVersion((version) => version + 1);
    }
    return { resources, isLoading, error, refetch };
    }

    The hook starts in a loading state. A successful response supplies an array; a failed request supplies an error. fetch doesn’t reject merely because the server returns an HTTP error status, so we check response.ok ourselves.

    The Effect owns each request and its controller. Cleanup aborts that request when the hook unmounts or another request version replaces it. Checking the signal before every completion update prevents an obsolete request from changing the resources, error, or loading state.

    refetch clears the error, shows loading, and changes a dependency. React then cleans up the previous Effect and starts a fresh request. Retry requests get the same cleanup as the first request.

    Notice that the Effect callback itself isn’t async. It must return a cleanup function, not a Promise. The asynchronous work lives in the inner function.

  4. Replace the static resource source.

    Import the hook into App and call it alongside the other hooks, before return.

    src/App.jsx
    import { useSelectedResource } from './hooks/useSelectedResource';
    import { useResources } from './hooks/useResources';
    src/App.jsx
    const [virtualOnly, setVirtualOnly] = useState(false);
    const { resources, isLoading, error, refetch } = useResources();
    return (

    Add the array to the existing Results props; keep all the filter and selection props.

    src/App.jsx
    <Results
    resources={resources}
    selectedResource={selectedResource}
    onSelectResource={setSelectedResource}

    In Results, remove the local data import and receive that prop instead.

    src/components/Results.jsx
    import ResultsItem from './ResultsItem';
    import { resources } from '../data/resources';
    import Card from './ui/Card';
    export default function Results({ selectedResource, searchTerm, selectedCategories, onSelectResource, openNowOnly, virtualOnly }) {
    export default function Results({ resources, selectedResource, searchTerm, selectedCategories, onSelectResource, openNowOnly, virtualOnly }) {

    Leave its filtering and .map() logic in place. Refresh and check the Network panel for GET /resources. Results should now display backend data. The UI may briefly show an empty list; let’s describe that waiting state properly.

  5. Render loading, error, or results in the same grid position.

    In App, wrap the existing Results component with a conditional inside its current <section>. These two diffs show the beginning and end of that same section; retain all the props between them.

    src/App.jsx
    <section className="md:col-span-2 lg:col-span-1">
    {isLoading ? (
    <p role="status" className="text-sm">Loading resources...</p>
    ) : error ? (
    <div role="alert" className="alert alert-error">
    <div>
    <p className="font-semibold">Could not load resources</p>
    <p>{error.message}</p>
    <button type="button" className="btn btn-sm mt-2" onClick={refetch}>
    Try again
    </button>
    </div>
    </div>
    ) : (
    <Results
    resources={resources}
    src/App.jsx
    openNowOnly={openNowOnly}
    virtualOnly={virtualOnly}
    />
    )}
    </section>

    Loading and errors now occupy the Results column instead of becoming extra grid items. Filters and Details keep their existing positions.

  6. Test the request lifecycle.

    Use DevTools network throttling and refresh. You should see Loading resources before the list appears. Then stop the backend with Ctrl+C in its own terminal and refresh the frontend. You should see the error and Try again button.

    Restart the backend with pnpm start, then click Try again without refreshing the browser. The list should return. Restore normal network speed afterward.

    Keep Strict Mode enabled. An aborted development request shouldn’t display an error or hide the loading message for the current request.

  7. Verify that clearing selection is persisted too.

    Add a button before the existing details conditional in App.

    src/App.jsx
    <aside className="md:col-span-1 lg:col-span-1">
    <button type="button" className="btn btn-sm btn-outline mb-3"
    disabled={selectedResource === null}
    onClick={() => setSelectedResource(null)}>
    Clear selection
    </button>
    {selectedResource ? (
    <Details resource={selectedResource} />

    Select, refresh, clear, and refresh again. The final refresh should show the selection prompt, and Session Storage should no longer contain the key.

Our two hooks now have distinct jobs. useSelectedResource synchronizes selection with storage. useResources manages an asynchronous read and exposes enough state for the UI to explain what’s happening.

The saved selection is still a resource snapshot. Fetching a new list doesn’t automatically update that saved object. Consider how storing an id and looking up the current object would change this design.


  • Add an Effect that updates document.title with the selected resource’s title, or a default when nothing is selected. Restore the previous document title in cleanup.
  • Add a temporary console log to observe changes in selection. Explain why its dependency array contains selectedResource.
  • Add a no-results message that appears only after a successful request when the filtered list is empty. Distinguish an empty response from a failed request.

Before experimenting with a missing dependency array, predict what will happen. In particular, a fetching Effect that updates state after every commit can cause a repeated-request loop.

Continue the same project using today’s homework.md. Refactor useSelectedUser so an Effect persists the selected user id, then replace the local data with JSONPlaceholder.

Use these endpoints:

  • https://jsonplaceholder.typicode.com/users for the user list.
  • https://jsonplaceholder.typicode.com/posts?userId=ID for the selected user’s posts.

Your solution should have separate loading and error feedback for users and posts. Check HTTP status, clean up pending requests, and ignore obsolete completions. When selection becomes null, clear the posts and show the selection prompt. While loading another user’s posts, don’t present the previous user’s posts as the new user’s results.

Test a refresh with a saved selection, clearing selection, a failed request, and rapid selection changes under network throttling. The final posts must always belong to the currently selected user. Keep your existing submit-based user search working.

The starter’s homework snippets are sketches; apply the status checks and cleanup from this activity when implementing them. In your README.md, explain why fetching during rendering is unsuitable and how your dependency arrays connect requests to selection. Follow the starter’s submission instructions after checking the behaviour.