Handling race conditions
If your component makes several requests quickly, it can lead to a race condition that can create unpredictable or incorrect results. Network requests are asynchronous; therefore, requests don’t necessarily finish in the same order as they were sent.
The following example code sends a network request when the props.carid
value changes:
import { useEffect, useState } from 'react';
function CarData(props) {
const [data, setData] = useState({});
useEffect(() => {
fetch(`https ://carapi .com/car/${props.carid}`) .then(response => response.json())
.then(cardata => setData(cardata))
}, [props.carid]);
if (data) {
return <div>{data.car.brand}</div>;
} else {
return null;
}
continue...
Now, if carid
changes quickly multiple times, the data that is rendered might not be from the last request that was sent.
We can use the useEffect
cleanup function to avoid race conditions. First...