There are generally two rules for React Hooks:

Rules of React Hooks

  • must be defined within a React component
  • must be defined at the “topmost” level

Why should one create custom React Hooks?

A custom Hook makes sense when code state is involved and needs to be used across multiple components.

Example Definition of a Hook

//useFetch.js
import { useEffect, useState } from "react";

export function useFetch(fetchFn, initialValue) {
    const [fetchedData, setFetchedData] = useState(initialValue);
    const [isFetching, setIsFetching] = useState(false);
    const [error, setError] = useState();

    useEffect(() => {
        async function fetchData() {
            setIsFetching(true);
            try {
                const data = await fetchFn();
                setFetchedData(data);
            } catch (error) {
                setError({ message: error.message || 'Failed to fetch data.' });
            }
            setIsFetching(false);
        }
        fetchData();
    }, [fetchFn]);

    return {
        isFetching,
        fetchedData,
        setFetchedData,
        error
    }
}

Example Usage of the Hook

//App.jsx

function App() {
  const { isFetching, error, fetchedData: userPlaces, setFetchedData: setUserPlaces } = useFetch(fetchUserPlaces, []);

... Restlicher Code
}

export default App;