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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Recursive setTimeout lets you poll only while work remains, avoiding wasted requests once a terminal state is reached.
- 2Returning a cleanup function that aborts the fetch and clears the timer prevents state updates after unmount.
- 3Encapsulating fetch, state, and lifecycle inside a hook gives components a clean status/result/error interface.
Related explainers
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 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
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/polling-a-job-status-with-a-react-hook-explained-javascript-9dfa/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.