Next.js useEffect Hook: Side Effects & Cleanup

💪 Day 3/30 — Next.js & MERN Stack Interview Prep Q: What is useEffect and how do you handle side effects in Next.js? 🏂 Short Answer: useEffect is a React hook that lets you run side effects — like data fetching, subscriptions, or DOM manipulation — after a component renders. 🔍 The Full Answer: useEffect(() => { // your side effect here return () => { // cleanup (optional) }; }, [dependencies]); The dependency array controls WHEN it runs: [] → runs once on mount [value] → runs when value changes no array → runs after every render ⚠️ ⚡ In Next.js specifically — this matters: useEffect only runs on the client side. So in Next.js App Router, if you're using useEffect, your component must be marked as: "use client"; Server Components can't use useEffect at all. 🧠 A common interview trap: useEffect(() => { fetch("/api/data") .then(res => res.json()) .then(data => setData(data)); }, []); // ✅ runs once Interviewers love asking: "What happens if the component unmounts before the fetch completes?" Answer: You get a memory leak. Fix it with a cleanup flag or AbortController: useEffect(() => { const controller = new AbortController(); fetch("/api/data", { signal: controller.signal }) .then(res => res.json()) .then(data => setData(data)) .catch(err => { if (err.name !== "AbortError") console.error(err); }); return () => controller.abort(); }, []); 🏌️ Key Takeaways: useEffect = side effects after render Always think about the dependency array In Next.js App Router → needs "use client" Clean up async effects to avoid memory leaks Follow for Day 4 tomorrow! 🔔 #NextJS #React #JavaScript #WebDevelopment #InterviewPrep #MERN #30DayChallenge #FrontendDeveloper

To view or add a comment, sign in

Explore content categories