javascript 47 lines · 8 steps

Polling a job status with a React hook

A custom hook that repeatedly fetches a job's status until it completes or fails, cleaning up on unmount.

Explained by highlit
1import { useEffect, useState } from 'react';
2 
3export function useJobStatus(jobId, { interval = 3000 } = {}) {
4 const [status, setStatus] = useState('pending');
5 const [result, setResult] = useState(null);
6 const [error, setError] = useState(null);
7 
8 useEffect(() => {
9 if (!jobId) return;
10 
11 let timerId;
12 const controller = new AbortController();
13 
14 const poll = async () => {
15 try {
16 const res = await fetch(`/api/jobs/${jobId}`, {
17 signal: controller.signal,
18 });
19 if (!res.ok) throw new Error(`Request failed: ${res.status}`);
20 
21 const data = await res.json();
22 setStatus(data.status);
23 
24 if (data.status === 'completed') {
25 setResult(data.result);
26 } else if (data.status === 'failed') {
27 setError(new Error(data.message ?? 'Job failed'));
28 } else {
29 timerId = setTimeout(poll, interval);
30 }
31 } catch (err) {
32 if (err.name !== 'AbortError') {
33 setError(err);
34 }
35 }
36 };
37 
38 poll();
39 
40 return () => {
41 controller.abort();
42 clearTimeout(timerId);
43 };
44 }, [jobId, interval]);
45 
46 return { status, result, error };
47}
01 / 01
STEP 01

Walkthrough

Space play ←→ step click any line
Three takeaways
  1. 1Recursive setTimeout lets you poll only while work remains, avoiding wasted requests once a terminal state is reached.
  2. 2Returning a cleanup function that aborts the fetch and clears the timer prevents state updates after unmount.
  3. 3Encapsulating fetch, state, and lifecycle inside a hook gives components a clean status/result/error interface.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Polling a job status with a React hook — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code