💡 𝐑𝐞𝐚𝐜𝐭 𝐇𝐨𝐨𝐤 – 𝐮𝐬𝐞𝐄𝐟𝐟𝐞𝐜𝐭 (API Call + Dependency Array) ❓ How do we fetch data from an API in React 𝘄𝗶𝘁𝗵𝗼𝘂𝘁 𝗶𝗻𝗳𝗶𝗻𝗶𝘁𝗲 𝗿𝗲-𝗿𝗲𝗻𝗱𝗲𝗿𝘀? Today I learned how useEffect is used for 𝗔𝗣𝗜 𝗰𝗮𝗹𝗹𝘀 and how the 𝗱𝗲𝗽𝗲𝗻𝗱𝗲𝗻𝗰𝘆 𝗮𝗿𝗿𝗮𝘆 controls when the effect runs 🚀 🔹 𝗪𝗵𝘆 𝘂𝘀𝗲𝗘𝗳𝗳𝗲𝗰𝘁 𝗳𝗼𝗿 𝗔𝗣𝗜 𝗰𝗮𝗹𝗹𝘀? 👉 React re-renders components often 👉 API calls should 𝗻𝗼𝘁 𝗿𝘂𝗻 𝗼𝗻 𝗲𝘃𝗲𝗿𝘆 𝗿𝗲𝗻𝗱𝗲𝗿 👉 useEffect helps control this behavior 🔹 𝗞𝗲𝘆 𝗽𝗼𝗶𝗻𝘁𝘀: 🔹 useEffect is used to handle 𝘀𝗶𝗱𝗲 𝗲𝗳𝗳𝗲𝗰𝘁𝘀 🔹 API calls are usually written 𝗶𝗻𝘀𝗶𝗱𝗲 𝘂𝘀𝗲𝗘𝗳𝗳𝗲𝗰𝘁 🔹 The 𝗱𝗲𝗽𝗲𝗻𝗱𝗲𝗻𝗰𝘆 𝗮𝗿𝗿𝗮𝘆 decides 𝘄𝗵𝗲𝗻 useEffect runs 🔹 𝗪𝗵𝗮𝘁 𝗱𝗼𝗲𝘀 𝘁𝗵𝗲 𝗱𝗲𝗽𝗲𝗻𝗱𝗲𝗻𝗰𝘆 𝗮𝗿𝗿𝗮𝘆 𝗱𝗼? 👉 [] → runs 𝗼𝗻𝗹𝘆 𝗼𝗻𝗰𝗲 when the component mounts 👉 [id] → runs when 𝗶𝗱 changes 👉 No array → runs on 𝗲𝘃𝗲𝗿𝘆 𝗿𝗲𝗻𝗱𝗲𝗿 ❌ 📌 This is why the dependency array is 𝘃𝗲𝗿𝘆 𝗶𝗺𝗽𝗼𝗿𝘁𝗮𝗻𝘁. Next up: 𝘂𝘀𝗲𝗘𝗳𝗳𝗲𝗰𝘁 cleanup function or real-world API handling? 🤔 #ReactJS #JavaScript #useEffect #APICall #ReactHooks #FrontendDevelopment #LearningInPublic
You can use if condition with useRef to escape infinity render
Awesome notes! One thing that helped me was thinking of useEffect as syncing React with the outside world, while the dependency array just defines when that sync should happen. Would love to see a cleanup example next.
good
Nice 👍
Next step is cleanup + cancellation. Real apps need aborting in-flight requests, handling stale responses, and guarding against unmounts — that’s where useEffect gets interesting. But anyway: import { useEffect, useState } from "react"; function Users({ id }) { const [users, setUsers] = useState([]); const [error, setError] = useState(null); useEffect(() => { const controller = new AbortController(); const signal = controller.signal; async function fetchUsers() { try { const res = await fetch( `https://jsonplaceholder.typicode.com/users`, { signal } ); const data = await res.json(); setUsers(data); } catch (err) { if (err.name !== "AbortError") { setError(err); } } } fetchUsers(); // 👇 cleanup return () => { controller.abort(); }; }, [id]); // re-run if id changes if (error) return <p>Error loading users</p>; return ( <ul> {users.map(u => ( <li key={u.id}>{u.name}</li> ))} </ul> ); }