Using the Fetch API in React with functional components
Last updated: September 27, 2022.
You can use JavaScript’s native Fetch API to make GET, POST, PUT and DELETE requests in React.
There are two ways to do this. One option is to call fetch()
inside a component.
Another option is to create a custom and reusable fetch hook that handles requests externally. This avoids repetitive syntax and reduces the amount of code in your components.
Table of contents
Calling fetch()
inside a component
One option for doing this is to make a request inside a component.
To print the result to the DOM, use the useState()
hook to update the state value to the print value.
The fetch request itself should be made inside the useEffect()
hook. This means it will only run once, after the component has rendered. Include []
as a second argument to specify that the updating of no element should cause useEffect()
to run again.
Inside the return statement, use &&
to only render the right-side value when the value of content
is no longer falsy.
import { useState, useEffect } from "react";
function App() {
const [content, setContent] = useState(null);
useEffect(() => {
fetch('https://httpbin.org/get')
.then(res => res.json())
.then(res => {setContent(res); console.log(res);})
.catch(err => console.log(err));
},[]);
return (
{content && content.headers.Origin}
);
}
export default App;
[]
as a second argument in useEffect()
, an infinite loop of requests will occur! This is because printing the result to the DOM will cause a re-rendering, which will cause useEffect()
to run again, print to the DOM again, causing another re-rendering, etc. The second parameter specifies the elements that would need to change in order to cause useEffect()
to run again. Passing in []
specifies that nothing should trigger useEffect()
again.
Making fetch()
reusable with a custom hook
The advantage of creating a custom hook for using fetch()
is that you can then call it in one line within components of your app. It also avoids repetition of fetch syntax in multiple components.
Creating the hook
To create the hook, create a component with a parameter of url
. Inside the component, call fetch()
within useEffect()
.
To trigger useEffect()
to run every time a call is made to use the hook, pass in [url]
as the second argument. Now, every time useFetch()
is called, url
will update, and the hook will run.
/* useEffect.js */
import { useState, useEffect } from "react";
function useFetch(url) {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(res => setData(res))
.catch(err => setError(err));
},[url]);
return { data, error };
}
export default useFetch;
Using the hook
Now, inside a component, you can call useFetch()
after importing it. Use object destructuring to access the result and &&
to ensure that nothing is rendered until the value of data
is truthy.
/* App.js */
import useFetch from "./useFetch";
function App() {
const { data, error } = useFetch('https://httpbin.org/get');
return (
{data && data.headers.Origin}
);
}
export default App;
Related links
- React.js documentation: Using the State Hook
- React.js documentation: Using the Effect Hook
- OpenJavaScript: Using fetch to make GET, POST, PUT and DELETE requests
- OpenJavaScript: Make fetch GET, POST, PUT and DELETE requests in a single line