,

Implementing fetch API in React JS using useEffect and custom hook

Posted by






Using fetch API in React JS

Using fetch API in React JS (with useEffect & custom hook)

React is a popular JavaScript library for building user interfaces. It provides a powerful way to fetch data from an API using the fetch API. In this article, we will discuss how to use the fetch API in a React component, along with the useEffect hook and a custom hook for data fetching.

Creating a custom hook for data fetching

First, let’s create a custom hook for fetching data from an API. We’ll call this hook useFetch.

“`jsx
import { useState, useEffect } from ‘react’;

const useFetch = (url) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);

useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(url);
const json = await response.json();
setData(json);
setLoading(false);
} catch (error) {
console.error(‘Error fetching data:’, error);
setLoading(false);
}
};

fetchData();
}, [url]);

return { data, loading };
};

export default useFetch;
“`

In this custom hook, we use the useState and useEffect hooks to manage the state and perform the data fetching. The useFetch hook takes a URL as an argument and returns the fetched data and a loading indicator.

Using the custom hook in a React component

Now that we have our custom hook for data fetching, let’s see how we can use it in a React component.

“`jsx
import React from ‘react’;
import useFetch from ‘./useFetch’;

const MyComponent = () => {
const { data, loading } = useFetch(‘https://api.example.com/data’);

if (loading) {
return

Loading…

;
}

return (

Data:

{JSON.stringify(data, null, 2)}

);
};

export default MyComponent;
“`

In this example, we import the useFetch hook and use it to fetch data from ‘https://api.example.com/data’. We then render the data if it has been fetched, or a loading indicator if the data is still being fetched.

Conclusion

Using the fetch API in a React component with the useEffect hook and a custom hook for data fetching is a powerful way to manage data fetching and state in a React application. This approach provides a clean and reusable way to fetch data from an API and handle loading states.


0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
The Soul Crisis
7 months ago

Hello mate, thank you for the swell tutorial! I am currently building a personal site with React pulling data from WordPress REST API! This is hands down one of the best and most versatile fetch API + React tutorials I've come across. Immaculate job explaining the steps and your reasoning in the approach to constructing the solution.

I love the twist at the end and now know how to create custom hooks in React, plus it worked pretty much out of the box for me! I'm dealing with a few annoying quirks that the WordPress REST API presents but this tutorial itself is gold. I don't know how it doesn't have any comments or more views to be honest, for me it's stellar and thanks for making it.

You have earned yourself a sub. ^_^