Timers in React often start simple… then you hit stale closures, re-renders, and “why is my interval running twice?” 😅
A small custom hook like useInterval keeps the logic clean and ensures the interval is properly cleared (bye bye memory leaks 👋).
🔸 TL;DR
You can encapsulate setInterval + cleanup into a useInterval hook to make timer logic reusable, readable, and safer in React.
🔸 THE HOOK (CODE SNIPPET)
🔸 WHEN TO USE IT
▪️ Live clocks 🕒
▪️ Auto-refresh dashboards 📊
▪️ Polling an API (careful with rate limits) 🌐
▪️ Carousels / rotating tips 🎠
▪️ Background updates 🔁
🔸 IMPORTANT NOTE (COMMON PITFALL)
Because the hook depends on [fn, delay], if fn changes on each render, the interval will restart each time.
✅ Tip: wrap fn with useCallback(...) to keep it stable, or use a ref-based implementation when you need the latest callback without resetting the interval.
🔸 TAKEAWAYS
▪️ Always clear intervals in useEffect cleanup 🧹
▪️ Stabilize fn (e.g., useCallback) to avoid interval resets ♻️
▪️ Great for repeating side-effects without duplicating boilerplate ✅
#React #JavaScript #Frontend #WebDev #Hooks #useEffect #CleanCode #SoftwareEngineering #DevTips #Programming
🏆 Thrive at React job interviews: https://www.udemy.com/course/react-reactjs-questions-and-answers-2023-job-interviews/?referralCode=C52F8C70EFA5555C18AC