Editorial Q&A · This problem and its answer were written by the TechLab editorial team to document a common issue. It isn't a question from a community member. If you've hit a variation of it or know a better approach, add a reply below.
The setup
A monitoring dashboard built with React and axios has several tabs. Each one renders a PerformanceMetric component that fetches time-series data (CPU, memory, network) for its metricId. Users switch tabs quickly, so these components mount, unmount and change props while requests are still in flight.
The problem
The PerformanceMetric component uses useEffect to fetch data when it mounts or when its metricId prop changes. We display a loading spinner while data is being fetched and an error message if the API call fails.
Two symptoms show up when users switch tabs quickly. On React 17, the console fills with this warning whenever a component unmounts before its request finishes:
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
at PerformanceMetric (http://localhost:3000/static/js/main.chunk.js:1234:5)
at div
... (truncated stack trace)React 18 removed that warning, so after upgrading the console goes quiet. The second symptom remains in every version, and it's the one users notice: when metricId changes quickly (CPU → Memory → CPU), the chart sometimes shows data for the wrong metric. A slow response from an earlier request arrives after a faster later one and overwrites it.
The code
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Spinner, Alert } from 'some-ui-library'; // Placeholder for UI components
interface PerformanceMetricProps {
metricId: string;
timeRange: string; // e.g., '1h', '24h', '7d'
}
interface MetricData {
timestamp: number;
value: number;
}
const PerformanceMetric: React.FC<PerformanceMetricProps> = ({ metricId, timeRange }) => {
const [data, setData] = useState<MetricData[] | null>(null);
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
setLoading(true);
setError(null);
setData(null); // Clear previous data
const fetchMetricData = async () => {
try {
const response = await axios.get<MetricData[]>(
`/api/metrics/${metricId}?range=${timeRange}`
);
setData(response.data);
} catch (err) {
if (axios.isAxiosError(err)) {
setError(err.message);
} else {
setError('An unknown error occurred.');
}
} finally {
setLoading(false);
}
};
fetchMetricData();
// No cleanup function: nothing stops an old request from updating state
}, [metricId, timeRange]);
if (loading) {
return <Spinner message={`Loading ${metricId} data...`} />;
}
if (error) {
return <Alert type="error" message={`Failed to load ${metricId}: ${error}`} />;
}
if (!data || data.length === 0) {
return <Alert type="info" message={`No data available for ${metricId}.`} />;
}
return (
<div className="performance-metric-chart">
<h3>{metricId} Data</h3>
{/* Render chart here using 'data' */}
<pre>{JSON.stringify(data.slice(0, 5), null, 2)}...</pre>
</div>
);
};
export default PerformanceMetric;Expected behaviour
When the component unmounts or its props change, responses to the old request are ignored, and the chart always shows the most recently requested metric.
Actual behaviour
Responses from superseded requests still call setData, setError and setLoading. On React 17 that produces the unmounted-component warning. On any version it can display stale data for the wrong metric.
The question: how should the effect handle requests that are still pending when the component unmounts or its dependencies change?
