Skip to main content

useLongTasks

Description and use case

useLongTasks wraps PerformanceObserver for the longtask entry type. It records main-thread tasks over 50 ms, keeps a bounded history, and attaches each freeze to a screen, route, or view name.

API signature

function useLongTasks(options?: UseLongTasksOptions): UseLongTasksReturn;

Parameters

NameTypeRequiredDescription
options.onLongTask(metric: LongTaskMetric) => voidNoCallback fired for each retained long task.
options.screenstring | (() => string | null | undefined) | nullNoScreen, route, or view attached to each metric.
options.minDurationnumberNoMinimum task duration retained by the hook. Defaults to 50.
options.maxEntriesnumberNoMaximum metrics retained in state. Defaults to 50.
options.enabledbooleanNoSet false to disable the observer.

Return value

FieldTypeDescription
latestLongTaskMetric | nullLatest retained long task.
entriesLongTaskMetric[]Retained long-task metrics for debugging and overlays.
countnumberNumber of retained long tasks.
totalBlockingTimenumberSum of retained blockingTime values.
isSupportedbooleanWhether this browser supports Long Tasks entries.

Live interactive demo (StackBlitz)

GitHub Pages does not serve the isolation headers required for embedded StackBlitz WebContainers. Open the demo in StackBlitz to run it interactively.

Code example

import { useLongTasks } from 'react-perf-hooks';

export function LongTaskProbe() {
const { latest, count, totalBlockingTime, isSupported } = useLongTasks({
screen: () => location.pathname,
minDuration: 75,
onLongTask: (metric) => {
navigator.sendBeacon('/api/long-tasks', JSON.stringify(metric));
},
});

if (!isSupported) {
return <p>Long Tasks API is not available in this browser.</p>;
}

return (
<p>
Long tasks: {count}, total blocking: {totalBlockingTime.toFixed(0)} ms, latest:{' '}
{latest ? `${latest.duration.toFixed(0)} ms on ${latest.screen}` : 'waiting'}
</p>
);
}

Companion article