How to Fetch Data With React Hooks

How to Fetch Data With React Hooks

Ferenc Almasi β€’ Last updated 2021 June 30 β€’ Read time 2 min read
  • twitter
  • facebook

To fetch data from your API using React hooks, you can introduce a custom useFetch hook that uses useState and useEffect internally:

Copied to clipboard! Playground
import { useState, useEffect } from 'react'

const useFetch = url => {
    const [state, setState] = useState([null, false]);

    useEffect(() => {
        setState([null, true]);

        (async () => {
            const data = await fetch(url)
                .then(res => res.json());

            setState([data.body, false]);
    }, [url]);

    return state;

export default useFetch;

This function returns an array with two variables: A post object, and a loading flag. By default, on line:4, you can see that we start out with null and false. There's nothing loading. But then we set loading to true on line:7, and inside an anonymous async function, we fetch the result. Once the result comes back, we can populate it into the post variable that is returned.

Note that you can't make the callback of useEffect async directly. Therefore, you have to define a sepearate async function inside it. And of course, once the data is returned, we can set the loading state back to false. You can pass the url into the dependency array of the useEffect. This tells React to only rerun the effect when the URL changes. To use this hook, you can introduce it in your component the following way:

Copied to clipboard! Playground
// After importing the useFetch hook
const Post = () => {
    const [post, loading] = useFetch('');
    if (loading) {
        return <Loading />

    return <PostBody content={post} />;

If you would like to see it in action, give it a try on Codesandbox

Try the hook on codesandbox
How to Fetch Data With React Hooks
If you would like to see more Webtips, follow @flowforfrank

If you are interested in reading more about React hooks, see more examples for custom hooks or just learn about the basics, make sure to check out the article below.

All You Need to Know About React Hooks
  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:



This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.