DEV Community

Cover image for Create custom fetch hook in react
Rajasekar Thangavel
Rajasekar Thangavel

Posted on • Updated on

Create custom fetch hook in react

Custom hook useFetch

import { useState, useEffect } from 'react';

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

    useEffect(() => {
        (async () => {
            try {
                const res = await fetch(url);
                const resJson = await res.json();
                setData(resJson);
            } catch (err) {
                setError(err);
            } finally {
                setLoading(false);
            }
        })();
    }, [url]);
    return { loading, data, error };
};

export default useFetch;
Enter fullscreen mode Exit fullscreen mode

usage

import useFetch from "./useFetch";
const { data, loading, error } = useFetch('https://jsonplaceholder.typicode.com/todos', []);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)