🧑🏾‍💻 prep

🐕 Fetching data

Learning Objectives

Often when you create a React app, you will want to fetch data from an API and display it inside your components. How do we do this in React?

You might think that we could just fetch the data in the component like this, but unfortunately it won’t work. Try it out in the CodeSandbox below.

This is because React is synchronous, while fetch is asynchronous. If we look in the console, we’ll see that the imgSrc will always be null when we try to render it. React will try to render before fetch has had time to get the data from the API.

So how do we fix this? We need to use a React hook called useEffect.