Today I learned how useEffect cleanup actually works in React — and it completely changed how I think about side effects. When we use useEffect, it runs after render. But what many beginners ignore is the cleanup function. Why is cleanup important? Prevents memory leaks Stops unnecessary API calls Removes event listeners properly Clears intervals and timeouts Example: When you add an event listener inside useEffect, you must remove it when the component unmounts. Otherwise, it keeps running in the background. That’s where cleanup comes in. useEffect(() => { const handleResize = () => console.log("Resized"); window.addEventListener("resize", handleResize); return () => { window.removeEventListener("resize", handleResize); }; }, []); The function returned inside useEffect runs: Before the next effect runs When the component unmounts Small detail. Big difference in performance. React is simple — until you understand the details. #ReactJS #FrontendDeveloper #JavaScript #WebDevelopment #LearningInPublic #100DaysOfCode
React useEffect Cleanup: Preventing Memory Leaks and Improving Performance
More Relevant Posts
-
Today something interesting happened while I was building a Custom Date Picker in NextJS.🗓 I have used useRef many times before, but honestly I was mostly using it without fully understanding the concept behind it But today… it finally clicked.💫 While implementing the feature, I realized that: • useRef creates a mutable object • The value is stored inside .current • The value persists between renders • Updating .current does not trigger a re-render • It can also be used to directly access DOM elements The most interesting part for me was understanding why React doesn't re-render when current changes. Sometimes you don’t truly understand a concept until you build something real with it. Small learning today, but a very satisfying one. 💫 What was the React concept that took you the longest to understand❓️ #React #JavaScript #FrontendDevelopment #ReactHooks #BuildInPublic #LearningJourney
To view or add a comment, sign in
-
JavaScript Event Loop – Quick Example Understanding the Event Loop is important for writing efficient asynchronous JavaScript. Example: console.log("Start") const prom = new Promise((res) => res(true)) setTimeout(() => console.log("setTimeout"), 0) process.nextTick(() => console.log("nextTick")) queueMicrotask(() => console.log("microtask")) console.log(prom) Output order will be: Start Promise { true } nextTick microtask setTimeout Why? Because JavaScript processes tasks in this order: 1. Synchronous code 2. Microtasks (nextTick, Promises, queueMicrotask) 3. Macrotasks (setTimeout, setImmediate) Understanding this helps when debugging async issues in frontend apps. #javascript #webdevelopment #frontend #vuejs #eventloop
To view or add a comment, sign in
-
𝗔 𝗦𝘂𝗯𝘁𝗹𝗲 𝗥𝗲𝗮𝗰𝘁 𝗕𝘂𝗴 𝗖𝗮𝘂𝘀𝗲𝗱 𝗯𝘆 𝗖𝗹𝗼𝘀𝘂𝗿𝗲𝘀 Sometimes a React bug isn’t really a React problem. It’s a JavaScript closure problem. Consider this example: A component sets an interval inside useEffect and logs the state value. At first glance, you might expect the console to print the latest value of count. But it doesn’t. It always prints 0. Why? Because the callback inside setInterval captured the value of count from the first render. This happens because of JavaScript closures. When the effect runs, it closes over the variables that existed at that moment. Since the dependency array is empty, the effect runs only once — so the interval keeps using the old value. One simple fix is to include the state in the dependency array so the effect runs again when the value changes. Understanding closures is important when working with: • useEffect • useCallback • useMemo • async callbacks Many confusing React bugs are actually JavaScript closure issues. 👇 Example comparison below Day 12/100 — sharing practical frontend engineering lessons. Have you ever run into a bug caused by closures in React? #ReactJS #FrontendEngineering #JavaScript #SoftwareDevelopment #WebDevelopment
To view or add a comment, sign in
-
-
React Hooks: useState vs useRef — Know the Difference When working with React functional components, two commonly used hooks are useState and useRef. While they may seem similar at first, they serve different purposes. -- useState * Used to store and manage component state * When the state updates, React re-renders the component * Ideal for data that affects the UI Example: const [count, setCount] = useState(0); -- useRef * Used to store mutable values that persist across renders * Updating a ref does NOT trigger a re-render * Commonly used for accessing DOM elements or storing previous values Example: const inputRef = useRef(null); -- Simple Rule to Remember: * If the value affects the UI → useState * If the value should persist but not trigger re-render → useRef Mastering these hooks helps you write cleaner and more efficient React components. #ReactJS #WebDevelopment #FrontendDevelopment #JavaScript #ReactHooks #SoftwareDevelopment
To view or add a comment, sign in
-
Built a Password Generator using React while learning React Hooks in depth. Worked with useState, useEffect, useCallback, and useRef to understand state management, DOM access, and performance optimization in a practical way. #ReactJS #WebDevelopment #Frontend #LearningInPublic #JavaScript
To view or add a comment, sign in
-
Just built a Login Page using React — and honestly, useState made it so clean! 🚀 The whole toggle between Sign In and Sign Up? Just one boolean state and a setFunction doing all the heavy lifting. ```jsx const [isSignIn, setIsSignIn] = useState(true); ``` No extra libraries. No complexity. Just props flowing down and a setter function flipping the view. It's one of those moments where React just *clicks* — you realize how powerful a single state value can be when your components are built right. If you're learning React, start here. Build a login page. Toggle two views with useState. You'll understand props and state faster than any tutorial. 💡 #React #ReactJS #useState #FrontendDevelopment #WebDevelopment #JavaScript #100DaysOfCode
To view or add a comment, sign in
-
In React, a Hook is just a JavaScript object. Each Hook stores: the state value a queue of updates and a reference to the next Hook Internally it looks like this: { memoizedState: state, queue: updates, next: nextHook } React stores Hooks as a linked list attached to the component's Fiber node. Fiber → Hook → Hook → Hook → null This is why Hooks must always be called in the same order. React reads them one by one during every render. When you call setState, React adds the update to the Hook's queue, and processes it during the next render. Hooks are not magic. They are simple objects connected together. Understanding this helps explain many React behaviors. #reactjs #javascript #webdevelopment
To view or add a comment, sign in
-
-
Where to Place Images in React.js & Next.js: A Quick Guide. One of the most common confusions for beginners (and even mid-level devs) is: "Where exactly should I put my images?" Here's a simple breakdown : ⚛️ React.js (CRA / Vite) /public — for static files accessed by URL (favicon, OG images) /src/assets — for images you import directly into components (better cache busting!) ▲ Next.js /public — same as React, served at the root URL. Use next/image component — always! It gives you lazy loading, WebP conversion & prevents layout shift automatically. → For external images (Cloudinary, Unsplash, CDN) — whitelist the domain in next.config.js first. 🏆 Golden Rules: ✅ Always use next/image in Next.js — never a plain <img> tag ✅ Import images in React for cache busting & tree shaking ✅ Keep /public only for files that need a fixed, stable URL ✅ Compress your images before uploading — optimization starts before the code! Small decisions like this make a big difference in performance and maintainability. #ReactJS #NextJS #WebDevelopment #Frontend #JavaScript #Programming
To view or add a comment, sign in
-
Want to learn more about React hooks? I recently stumbled upon BigFrontEnd.dev and have been really enjoying it. I’ve been spending some time in the React section, which has exercises where you predict what gets printed to the console when using React hooks. It’s been a great way to better understand how state updates work, when React re-renders a component, and how closures can affect values inside hooks. They also have a solid JavaScript section. I started exploring those to get a better feel for what actually gets logged when you combine things like console.log, setTimeout, and Promises. It’s been helpful for reinforcing how JavaScript handles execution order and the event loop. If you’ve been wanting to dig a little deeper into React hooks or brush up on JavaScript behavior under the hood, I highly recommend it Please let me know if there are any other great resources you use as well. #react #reacthooks #state #javascript
To view or add a comment, sign in
More from this author
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development