Sub topic 3
Loading Data Without Race Conditions
Assume you know function components, JSX, useState, useEffect, promises, and closures. Custom hooks can hide asynchronous work, subscriptions, and cleanup while keeping a component’s API small.
Loading data without race conditions
A race condition occurs when an older request finishes after a newer request and overwrites its result. Abort the old request and ignore results that are no longer relevant.
import { useEffect, useState } from 'react';
export function useFetchJson(url) {
const [state, setState] = useState({ status: 'loading', data: null });
useEffect(() => {
let ignore = false;
const controller = new AbortController();
setState({ status: 'loading', data: null });
fetch(url, { signal: controller.signal })
.then((response) => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
})
.then((data) => {
if (!ignore) setState({ status: 'success', data });
})
.catch((error) => {
if (!ignore && error.name !== 'AbortError') {
setState({ status: 'error', data: null, error });
}
});
return () => {
ignore = true;
controller.abort();
};
}, [url]);
return state;
}Reading the latest callback through a ref
A ref stores a mutable value without causing a render. Store the newest callback in a ref when an effect should keep one listener but call current logic. Include only the subscription inputs, such as type and target, in the subscription effect’s dependencies.
Subscribing to browser and external state
For browser state or another store that exists outside React, use useSyncExternalStore. It requires a subscribe function, a snapshot function, and a server snapshot when server rendering is possible.
const online = useSyncExternalStore(
(notify) => {
addEventListener('online', notify);
addEventListener('offline', notify);
return () => {
removeEventListener('online', notify);
removeEventListener('offline', notify);
};
},
() => navigator.onLine,
() => true
);Building, testing, and typing hooks
A larger hook can compose smaller hooks, such as useFetchJson plus useOnlineStatus. Each call still owns separate state.
Test hooks with renderHook and wrap updates in act:
const { result } = renderHook(() => useToggle());
act(() => result.current[1]());
expect(result.current[0]).toBe(true);Type the public contract explicitly:
export function useToggle(initial = false): readonly [boolean, () => void] {
const [on, setOn] = useState(initial);
return [on, () => setOn((value) => !value)] as const;
}Pitfalls and plain functions
Keep dependencies complete. Clean up timers, listeners, and requests. Do not call hooks conditionally or inside loops. A hook is unnecessary when code is pure and needs no React state, effects, refs, or subscriptions. Use a plain function for that logic.
Exercise
Why should a data-loading hook abort an old request and ignore its result?
Show answer
A newer request may already represent the current URL. Without cleanup, the older response can overwrite newer state.