Race conditions can occur when multiple API calls are made in quick succession. One such instance can be, when a user types rapidly into a search field. If earlier requests return after newer ones, outdated data can overwrite the latest results. We can prevent this by using the AbortController API to cancel in-flight requests before starting a new one. This ensures only the most relevant response updates the state.
useEffect(() => { const controller = new AbortController(); const fetchData = async () => { try { const response = await fetch(`/api/data?query=${query}`, { signal: controller.signal, }); const result = await response.json(); setData(result); } catch (err) { if (err.name !== 'AbortError') { console.error('API Error:', err); } } }; fetchData(); return () => { controller.abort(); // Cancels the previous request };
}, [query]);