How to Fetch API Data using useEffect
How to safely call an external API and manage loading states in React.
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).
Import and Call useEffect
Import the useEffect hook from 'react' and call it inside your component body. Pass it an arrow function.
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.
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.
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).
Handle the Error State
In the catch block, intercept any network failures and call setError(error.message).
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.
Invoke the Function
Immediately call fetchData() right after defining it inside the useEffect.
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.

