Learning about Async React

Natalia Wit
2 min readOct 25, 2020

--

Let’s think about a few social media sites we use on an everyday basis, such as Facebook or Instagram. When visiting those sites you see a bunch of posts of your friends. Each user that signs in has its own unique feed, depending on who you follow and a whole Facebook/Instagram algorithm. Facebook and Instagram are websites that are built in React. Every time you visit or even refresh the site, what will render first is the components of the website. Sometimes you may notice that component will load without an actual picture because of slow internet connection/sudden loss of connection. In this case, you are seeing React mounting the basic components and once they are mounted then the remote data will be requested. Once the data is received it will update the components with the pictures and user information. The data that we are speaking about might be a JSON object that is specific to the user or even the content requested. Those objects contain all the information we are requesting.

Component Lifecycle — componentDidMount

A very useful component lifecycle method that's commonly used in React is componentDidMount, inside that method we make our fetch requests. What makes componentDidMount a useful method is when making our fetch() request we can setState to store the data that we receive. This causes an update synced with the remote data. Here is an example:

Let’s go over what happens in the above example — once the App component mounts then a fetch() is called to an external API. Once we receive the data from the API, we store it in the state. The componentDidMount method is important to use when you need data to immediately load once a user visits your website.

You can also use a fetch() with events

You don't always have to use fetch only when a component is mounted. You can use them with events as well:

The above example allows us to make requests on a click event, meaning when we click a button we will be able to fetch some information.

Conclusion

You will run into cases where you will have to make choices on how to run your fetches. It will all depend on your project ideas. The general rule of thumb is to keep your fetch() calls in the same component where your top-level state is located, you can always pass down your methods as props if needed.

--

--

No responses yet