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
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
rust
use axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
javascript
function attachThousandSeparators(input, { locale = 'en-US' } = {}) { const formatter = new Intl.NumberFormat(locale); const groupSep = formatter.format(11111).replace(/\d/g, '')[0] || ','; const decimalSep = formatter.format(1.1).replace(/\d/g, '')[0] || '.';
Live thousand separators without losing the caret
dom
intl
caret-preservation
Advanced
8 steps
javascript
import { useReducer, useEffect } from "react"; const initialState = { status: "idle", data: null, error: null };
Building a data-fetching hook in React
custom-hooks
usereducer
data-fetching
Intermediate
9 steps
python
from functools import wraps import asyncio from fastapi import APIRouter, FastAPI, Request
Per-route request timeouts in FastAPI
decorators
async
timeouts
Intermediate
6 steps
javascript
const express = require('express'); const app = express(); app.get('/health', (req, res) => res.json({ status: 'ok' }));
Graceful shutdown in an Express server
graceful-shutdown
signal-handling
connection-tracking
Advanced
9 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.