javascript
41 lines · 9 steps
Building a data-fetching hook in React
A custom React hook that models async fetch state with a reducer and cancels stale requests.
Explained by
highlit
1import { useReducer, useEffect } from "react";
2
3const initialState = { status: "idle", data: null, error: null };
4
5function reducer(state, action) {
6 switch (action.type) {
7 case "FETCH_START":
8 return { ...state, status: "loading", error: null };
9 case "FETCH_SUCCESS":
10 return { status: "success", data: action.payload, error: null };
11 case "FETCH_ERROR":
12 return { ...state, status: "error", error: action.error };
13 default:
14 return state;
15 }
16}
17
18export function useUserProfile(userId) {
19 const [state, dispatch] = useReducer(reducer, initialState);
20
21 useEffect(() => {
22 const controller = new AbortController();
23
24 dispatch({ type: "FETCH_START" });
25
26 fetch(`/api/users/${userId}`, { signal: controller.signal })
27 .then((res) => {
28 if (!res.ok) throw new Error(`Request failed with ${res.status}`);
29 return res.json();
30 })
31 .then((data) => dispatch({ type: "FETCH_SUCCESS", payload: data }))
32 .catch((err) => {
33 if (err.name === "AbortError") return;
34 dispatch({ type: "FETCH_ERROR", error: err.message });
35 });
36
37 return () => controller.abort();
38 }, [userId]);
39
40 return state;
41}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Modeling async status as an explicit state machine beats juggling separate loading and error booleans.
- 2An AbortController cleanup keeps a stale request from writing state after the inputs change.
- 3A reducer plus useEffect packages fetch lifecycle logic into one reusable hook.
Related explainers
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
typescript
import { useEffect, useState } from "react"; interface Section { id: string;
Building a scroll-spy hook in React
custom-hooks
intersectionobserver
dom-observation
Intermediate
8 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
javascript
const { pool } = require('./db'); function withTransaction() { return async (req, res, next) => {
A per-request transaction middleware in Express
middleware
database-transactions
connection-pooling
Advanced
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-data-fetching-hook-in-react-explained-javascript-7e5f/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.