Skip to content

Custom Hooks and Persisted Selection

Our directory now connects filters, results, and details through shared state. Select a resource and refresh the browser. The selection disappears because a new instance of the application starts with useState(null).

Let’s make that selection survive a refresh. We’ll first move the existing state into a custom hook, check that the interface still works, and then add browser storage behind the hook’s interface.

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

  • Extract component state logic into a custom hook.
  • Explain the hook’s return values and where its state belongs.
  • Initialize state from stored JSON using an initializer function.
  • Store and clear a selected resource in sessionStorage.
  • Test persistence without confusing stored data with React state.

App needs to know which resource is selected and how to select another one. It doesn’t need to know the storage key, JSON format, or browser storage methods.

We’ll preserve this interface:

const [selectedResource, setSelectedResource] = useSelectedResource();

The first value is the current selection. The second is a function accepting a resource object or null. We’ll use the familiar setter name in App, but this first version won’t support React’s function-updater form.

A custom hook starts with use and composes other hooks. Each call has its own state; extracting a hook doesn’t create a shared global store. We will call this hook once, in App, and continue sharing its values through props. See React’s custom hooks guide.

Mechanism Responsibility in our app
React state Supplies the current selection for rendering
sessionStorage Keeps a serialized copy available after a refresh
Custom hook Coordinates reading, updating, and clearing the selection

Browser storage keeps strings, so we’ll use JSON.stringify when writing and JSON.parse when reading. sessionStorage is scoped to an origin and a browser tab’s page session. It survives reloads; it isn’t intended as permanent storage. Restored or duplicated tabs can retain or copy a session, so closing and reopening a tab is not a reliable clearing test. See MDN’s sessionStorage reference.

Rendering calculates what to display from props and state. React may repeat that calculation, so we shouldn’t write to storage or start requests in the component body. useEffect() lets us synchronize with something outside React after it commits an update to the UI.

Use an Effect when that synchronization should follow the component appearing or its props/state changing. For our selection, an Effect can keep sessionStorage up to date whenever selectedResource changes. Calculations such as filtering resources can happen during rendering; work tied to a specific click can stay in its event handler.

Today we’ll save through our update function; Lesson 16 will switch to an Effect. See React’s synchronizing with Effects guide.


From the root of your workbook, grab today’s starter for your section. If it’s already present, continue with that copy.

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

Open the URL printed by Vite. Today’s starter already has filtering, shared selection, and conditional details. Results still imports local resource data, so leave the backend stopped.

Paths below start inside src/lesson-15/frontend.

  1. Observe the behaviour we’re changing.

    Select a resource and confirm its details appear. Refresh the page. You should see the selection prompt again.

    Find const [selectedResource, setSelectedResource] = useState(null); in src/App.jsx. That’s the state we’ll extract. Search, categories, and the two filter checkboxes will keep their existing state.

  2. Extract the state before adding persistence.

    Create the src/hooks folder and a new useSelectedResource.js file.

    src/hooks/useSelectedResource.js
    import { useState } from 'react';
    export function useSelectedResource() {
    const [selectedResource, setSelectedResource] = useState(null);
    return [selectedResource, setSelectedResource];
    }

    Import the hook into App and replace the existing selection declaration.

    src/App.jsx
    import { useState } from 'react';
    import { useSelectedResource } from './hooks/useSelectedResource';
    src/App.jsx
    const [openNowOnly, setOpenNowOnly] = useState(false);
    const [selectedResource, setSelectedResource] = useState(null);
    const [selectedResource, setSelectedResource] = useSelectedResource();
    const [virtualOnly, setVirtualOnly] = useState(false);

    Keep the useState import: App still uses it for its other values. Keep the props passed to Results and Details as they are.

    Select a resource again. The interface should work exactly as before, including losing the selection after a refresh. We’ve changed where the logic is written; we haven’t added persistence yet.

  3. Read the saved selection when the state is initialized.

    Back in the hook, add a storage key and replace the null initial value with an initializer function.

    src/hooks/useSelectedResource.js
    import { useState } from 'react';
    const STORAGE_KEY = 'selectedResource';
    export function useSelectedResource() {
    const [selectedResource, setSelectedResource] = useState(null);
    const [selectedResource, setSelectedResource] = useState(() => {
    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 [selectedResource, setSelectedResource];
    }

    We pass a function instead of calling it ourselves. React uses it when initializing this instance’s state, rather than rereading storage on every update. This is lazy initialization. Development Strict Mode can call an initializer twice to check it, so this function only reads and returns a value; it doesn’t write to storage. See avoiding recreated initial state.

    The try block covers both storage access and JSON parsing. The small shape check rejects values such as a saved number or an unrelated object. This isn’t a full data validator; our app is saving its own resource objects.

    If there is no saved value, the selection still starts as null. We need to write something before a refresh can restore it.

  4. Save selections through the hook’s update function.

    Add a function before the hook’s return statement. It will update React state and attempt to save the supplied value.

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

    App still calls its second returned value setSelectedResource. It now receives our wrapper function instead of React’s setter directly. No change is needed in Results or Details.

    Select a resource and refresh. Its details and highlight should return. In DevTools, inspect Session Storage for the frontend’s origin. The selectedResource key should contain JSON for the selected resource.

    If storage is unavailable, selecting still updates the interface for the current visit. The console warning explains why persistence didn’t succeed.

  5. Give ourselves a clear-selection check.

    In App, add a button at the start of the details wrapper, before its existing conditional rendering.

    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 a resource, clear it, and refresh. The prompt should remain, and the storage key should be absent. This tests the null branch directly.

  6. Check more than the happy path.

    Use the following checks on the same frontend URL and port. Different ports use different origins and therefore different storage.

    Check Expected result
    Select A, then B, then refresh B returns
    Select, clear, then refresh No resource is selected
    Change only the search term, then refresh Selection returns; search resets
    Change the saved value to invalid JSON in DevTools, then refresh The app starts with no selection
    Remove only the selectedResource key and refresh The app starts with no selection

    Editing storage directly doesn’t call a React setter. That’s why these storage-edit checks include a refresh.

App still owns the selection through its hook call. The hook now hides the storage details behind a small interface, while Results and Details continue to receive props.

Writing to storage from an event-triggered update function is valid. In Lesson 16, we’ll explore a different requirement: keeping storage synchronized whenever selection state changes, using an Effect. That will also let us return React’s setter directly.

For now, we store a snapshot of the entire resource. If the original data changes, that snapshot can become stale. Storing only an id is a useful next design to consider.


  • Refactor the hook to store only the selected resource’s id. Decide where to find the current resource object and what to display if the id no longer exists.
  • Add a named clearSelectedResource function as a third return value. Keep the storage work inside the hook.
  • Create a small useBoolean hook for an unrelated toggle. Call it twice and confirm the calls have independent state.

Keep these extensions focused on custom hooks. We haven’t introduced useEffect yet.

Continue your Users and Posts project using today’s homework.md. Create src/hooks/useSelectedUser.js, returning the selected user id and a function that updates it.

Your solution should:

  • Restore the id using a lazy initializer and a project-specific storage key.
  • Save an id when selected and remove the stored value when selection becomes null.
  • Handle absent or malformed saved data without breaking the page.
  • Keep storage access inside the hook, with one hook call in the parent that shares selection.
  • Preserve the id’s type so comparisons against your user data still work.
  • Keep user highlighting, search, and post filtering working after the refactor.

Test selecting two users, refreshing, clearing, and refreshing again. Explain state ownership, lazy initialization, and the benefit of this hook in your README.md. No new dependencies or generic storage hook are needed. Follow the starter’s submission instructions when those checks pass.