The shown implementation is naive and prone to bugs, for example a race condition. If this id is rapidly changed (say from 1->2), and the first request arrives last, you think you are looking at user 2 but you've loaded data for user 1.
const [user, setUser] = useState<User | undefined>();
useEffect(() => {
const fetchUser = async () => {
const response = await fetch(`/api/users/${id}`);
const jsonData = await response.json();
setUser(jsonData);
};
fetchUser();
}, [id]);
If you don't know what you're doing, use Tanstack Query libs or read a better article.- https://tanstack.com/query/latest
- https://maxrozen.com/race-conditions-fetching-data-react-wit...