Standard Method
Using useEffect and fetch()β
π Why Use This Method?β
Using useEffect with fetch() is one of the simplest ways to fetch data in React applications. It is:
β Straightforward β No external dependencies, purely built-in React and JavaScript.
β Beginner-Friendly β Easy to understand and implement.
β Good for Small Apps β Suitable for applications that donβt require complex state management or caching.
However, this method is not the best choice if you need caching, automatic refetching, or global state management (for these, consider SWR or React Query).
β‘ How It Works?β
- The
useEffecthook runs after the component renders to fetch data asynchronously. fetch()makes an API request, waits for the response, and updates state variables.- The component re-renders when the state updates with new data.
π Code Example:β
import { useEffect, useState } from "react";
export default function FetchWithUseEffect() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch("https://api.example.com/data");
if (!response.ok) throw new Error("Failed to fetch data");
const result = await response.json();
setData(result);
} catch (error) {
setError(error.message);
} finally {
setLoading(false);
}
};
fetchData();
}, []); // Runs only once when the component mounts
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;
return <pre>{JSON.stringify(data, null, 2)}</pre>;
}
π§ Whatβs Happening Inside?β
- The component initializes three state variables:
data,loading, anderror. - The
useEffecthook runs only once after the first render ([]ensures it doesn't run on updates). - Inside
useEffect, an async function is defined and called immediately. fetch()requests data from the API:- β
If successful, the response is parsed as JSON and stored in
data. - β If thereβs an error,
erroris updated instead.
- β
If successful, the response is parsed as JSON and stored in
loadingis set tofalseonce data is fetched (or an error occurs).- The component re-renders and displays the fetched data.
Pros & Consβ
Advantagesβ
βοΈ Simple β No need for additional libraries.
βοΈ Quick Implementation β Just a few lines of code.
βοΈ Good for Small Projects β Works fine if caching or refetching isnβt required.
Disadvantagesβ
β No Caching β Fetches data again every time the component mounts.
β No Automatic Refetching β You must manually trigger updates.
β Limited Error Handling β No built-in retry mechanism.
β οΈ When Should You Avoid This Method?β
π« If you need caching, use SWR or React Query.
π« If multiple components share the same data, use React Query or a global store.
π« If you need real-time updates, consider WebSockets or polling strategies.