Simple way to fetch data with React Hook (useEffect)
“useEffect” is similar to a lifecycle method in React class. I would assume you already understand the basics of useEffect and useState. Nevertheless, I would like to show how I fetch API data and show it in the application.
- When we need to do something after render, we use React hook (useEffect) to handle the situation. So we need to import “useEffect” to the component as follows:
2. Import “useState” into the component and create variable dogImage and function setDogImage, and conditional (ternary) operation as follows:
This ternary state means if dogImage is true, it will show a dog image. If not, No Images text will be shown.
3. Next step is fetching data in “useEffect” function. In this case, we fetch data from the API and setDogImage to a url link to show a dog picture. When we finish all these steps, a dog image will be shown.
Additional: You can set conditional (ternary) operation to check if it is loading or not as follows: