Custom Hook : Simplify Code with Reusable Logic

The custom hook in React allows to write data-fetching logic once and reuse it across multiple components.


Setting up a reusable data-fetching function to simplify API calls and state management.

State Initialization with useState:

It initializes a data state variable with null as the default value, using React's useState hook. This variable will hold the fetched data.

import { useState, useEffect } from 'react';

function useFetch(url) {
    const [data, setData] = useState(null);
        // rest of the logic
}

Fetching Data with useEffect:

The useEffect hook runs whenever the url changes. It performs a fetch request to the specified url, parses the response as JSON, and updates data with the fetched result.

useEffect(() => {
        fetch(url)
                .then(response => response.json())
                .then(setData);
}, [url]);

Returning Data:

Finally, the function returns the data state variable so it can be used directly in any component that calls useFetch.

import { useState, useEffect } from 'react';

function useFetch(url) {
    const [data, setData] = useState(null);

    useEffect(() => {
        fetch(url)
            .then(response => response.json())
            .then(setData);
    }, [url]);

    return data;
}

Usage

const data = useFetch('https://api.example.com/data');

You Might Also Like

Default Props for Components

This code sets a default value for the text prop in the Button component. If no text prop is provide...

Conditional Rendering with Short Circuit

if you don’t need the else block while rendering components in React Js, you can do like this ```...