React Daq custom data-fetching hook mach
React codebase Hoch useEffect blocks law' (data fetch, loading state, error handling) ghaj. pattern wa' reusable hook Daq extract - typing Dach pagh, bugs subtle fix.
naive version 'ej Qagh
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
setLoading(true);
fetch(`/api/users/${userId}`)
.then((res) => res.json())
.then((data) => {
setUser(data);
setLoading(false);
});
}, [userId]);
if (loading) return <p>Loading...</p>;
return <h1>{user.name}</h1>;
}
Dun legh 'ach Qagh: userId nom choH vaj fetches law' wa'logh Qu'. latest response current userId rap Sov pagh. old slow request new fast request qaSDI' ghor vaj stale user render.
hook extract, cancellation rap
function useFetch(url) {
const [state, setState] = useState({ data: null, loading: true, error: null });
useEffect(() => {
let cancelled = false;
setState({ data: null, loading: true, error: null });
fetch(url)
.then((res) => {
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
return res.json();
})
.then((data) => {
if (!cancelled) setState({ data, loading: false, error: null });
})
.catch((error) => {
if (!cancelled) setState({ data: null, loading: false, error });
});
return () => {
cancelled = true;
};
}, [url]);
return state;
}
function UserProfile({ userId }) {
const { data: user, loading, error } = useFetch(`/api/users/${userId}`);
if (loading) return <p>Loading...</p>;
if (error) return <p>Something went wrong.</p>;
return <h1>{user.name}</h1>;
}
cancelled flag fix: url choH (pagh component unmount) vaj effect cleanup Qu' 'ej previous run cancelled true choH. old fetch tlhoy' vaj .then() flag legh 'ej bail out - stale data fresh state overwrite pagh.
AbortController boolean flag pagh
cancelled flag React stale response act Qotlh 'ach network request Qu'taH, bandwidth waste. AbortController in-flight request cancel:
function useFetch(url) {
const [state, setState] = useState({ data: null, loading: true, error: null });
useEffect(() => {
const controller = new AbortController();
setState({ data: null, loading: true, error: null });
fetch(url, { signal: controller.signal })
.then((res) => {
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
return res.json();
})
.then((data) => setState({ data, loading: false, error: null }))
.catch((error) => {
if (error.name !== 'AbortError') {
setState({ data: null, loading: false, error });
}
});
return () => controller.abort();
}, [url]);
return state;
}
error.name !== 'AbortError' check qatlh: fetch abort vaj promise reject, check pagh vaj cleanup abort Hoch error state set (component moved on).
manual refetch chel
fixed url dependency props choHDI' automatic refetch. 'ach "Retry" button same URL refetch poQ. url choH pagh effect trigger:
function useFetch(url) {
const [state, setState] = useState({ data: null, loading: true, error: null });
const [refetchIndex, setRefetchIndex] = useState(0);
useEffect(() => {
const controller = new AbortController();
setState({ data: null, loading: true, error: null });
fetch(url, { signal: controller.signal })
.then((res) => {
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
return res.json();
})
.then((data) => setState({ data, loading: false, error: null }))
.catch((error) => {
if (error.name !== 'AbortError') {
setState({ data: null, loading: false, error });
}
});
return () => controller.abort();
}, [url, refetchIndex]);
const refetch = () => setRefetchIndex((n) => n + 1);
return { ...state, refetch };
}
refetchIndex request choH pagh - dependency neH, callers url choH pagh rerun force.
hook Dochmey pagh
version building block Dun 'ach full data-fetching solution pagh. components law' same URL cache pagh, simultaneous requests dedupe pagh, transient failures retry pagh. React Query 'ej SWR libraries 'oH fill - useEffect + cancellation fundamentals lo', shared cache 'ej request deduplication chel. own version wa'logh mach Dun (yaj vaD). app data-dependent components law' vaj library lo'.
yaj
data-fetching hook state machine ghaH (idle → loading → success/error), useEffect cleanup Dun. cancellation logic optional pagh - pagh vaj props nom choH race conditions: old response new overwrite.