Facebook Pixel
Step-by-Step Guide

How to Fetch API Data using useEffect

How to safely call an external API and manage loading states in React.

  1. Initialize State Variables

    Create three state variables using useState: 'data' (initialized as null or empty array), 'isLoading' (initialized as true), and 'error' (initialized as null).

  2. Import and Call useEffect

    Import the useEffect hook from 'react' and call it inside your component body. Pass it an arrow function.

  3. Provide the Empty Dependency Array

    Crucially, pass an empty array [] as the second argument to useEffect. This guarantees the API call will only happen once when the component first mounts, preventing infinite loops.

  4. Define the Async Function

    Inside the useEffect callback, define an async function (e.g., const fetchData = async () => {...}). You cannot make the useEffect callback itself async.

  5. Execute the Try-Catch Block

    Inside fetchData, open a try-catch block. In the try block, await the fetch() call, parse the JSON response, and call setData(response).

  6. Handle the Error State

    In the catch block, intercept any network failures and call setError(error.message).

  7. Update the Loading State

    Add a 'finally' block to the try-catch, and call setIsLoading(false). This ensures the loading spinner stops regardless of whether the request succeeded or failed.

  8. Invoke the Function

    Immediately call fetchData() right after defining it inside the useEffect.

  9. Render Conditionally

    In your JSX return statement, use conditional rendering to show a spinner if isLoading is true, an error message if error is truthy, and the actual data if it successfully loaded.

Ready to master this completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.