Here’s an example of how you can add a loader on every API call in a React application using hooks and context for state management:
Step 1: Create a new context to manage the loading state.
import { createContext } from 'react'; const LoadingContext = createContext(false);
Step 2: Create a custom hook to toggle the loading state.
import { useState } from 'react'; function useLoading() { const [isLoading, setIsLoading] = useState(false); function startLoading() { setIsLoading(true); } function stopLoading() { setIsLoading(false); } return [isLoading, startLoading, stopLoading]; }
Step 3: In the component making the API call, use the custom hook and context to toggle the loading state before and after the API call.
import { useContext, useEffect } from 'react'; function DataFetcher() { const [isLoading, startLoading, stopLoading] = useLoading(); const { data, error, loading } = useFetch("https://jsonplaceholder.typicode.com/todos/1"); useEffect(() => { startLoading(); //API call stopLoading(); }, []); return ( <LoadingContext.Provider value={isLoading}> <div> {isLoading && <div className="loader"></div>} {error && <div>{error}</div>} {data && <div>{JSON.stringify(data)}</div>} </div> </LoadingContext.Provider> ); }
Step 4: In the component where you want to display the loader, import the context and use the state to conditionally render the loader.
import { useContext } from 'react'; function SomeComponent() { const isLoading = useContext(LoadingContext); return ( <div> {isLoading && <div className="loader"></div>} {/* other content */} </div> ); }
When the DataFetcher
the component is rendered, it will set the loading state to true, which will cause the loader component to be displayed. After the API call is complete, the loading state will be set to false, which will hide the loader component.
Note that this is a simplified example and in a real-world application, you might want to handle errors and loading state more explicitly and use useEffect
hook with proper dependency array and useFetch is a custom hook.