Avoiding Race Conditions when Fetching Data with React Hooks
▻https://hackernoon.com/avoiding-race-conditions-when-fetching-data-with-react-hooks-220d6fd0f66
Man jumping over clockAbout a month ago, I posted an example of fetching data using React Hooks to Twitter. While it was well-intended, Dan Abromov (of the React core team) let me know that my implementation contained a race condition. Consequently, I promised to write a blog post correcting my implementation. This is that post!Note: If this article helps you, please help spread the word by lending a clap (or 50)! ??SetupIn our example app, we are going to fake-load people’s profile data when their names are clicked. To help visualize the race condition, we’ll create a fakeFetchfunction that implements a random delay between 0 and 5 seconds.const fakeFetch = person => return new Promise(res => setTimeout(() => res($person's data
), Math.random() * 5000); );;Initial (...)
#react-hook #reactjs #front-end-development #asynchronous #javascript