⚠️ One tricky thing in React that confused me at first: useEffect dependencies At first, I thought useEffect just runs magically. But the truth is very simple 👇 🧠 Think of useEffect like this: “React, run this code after render, and re‑run it only when I tell you to.” That “telling” happens through the dependency array. ✅ Examples (super simple) useEffect(() => { console.log("Runs once"); }, []); ➡️ Runs only when component mounts but for the below case useEffect(() => { console.log("Runs when count changes"); }, [count]); ➡️ Runs every time count changes 🚨 The tricky part If you use a variable inside useEffect but forget to add it as a dependency, React will use an old value (stale data). 🧠 Rule to remember: If you use it inside useEffect, it should be in the dependency array. Once I understood this, useEffect stopped feeling scary 😊 Just logic + clarity. #React #JavaScript #Hooks #useEffect #Frontend #LearningInPublic
Mastering useEffect dependencies in React
More Relevant Posts
-
💡 useEffect Dependencies — Small Array, BIG Difference! One hook… three different behaviors — all based on the dependency array 🤯 Understanding this can save you from bugs and unnecessary re-renders! Let’s break it down 👇 🔹 1. No Dependency Array useEffect(() => { console.log("Runs on every render"); }); 👉 Runs after every render 👉 Can cause performance issues if not handled carefully 🔹 2. Empty Dependency Array [] useEffect(() => { console.log("Runs only once"); }, []); 👉 Runs only once (on mount) 👉 Perfect for: API calls Initial setup 🔹 3. With Dependencies [value] useEffect(() => { console.log("Runs when value changes"); }, [value]); 👉 Runs only when specific values change 👉 Best for syncing state, props, or side effects 🔁 Quick Summary No array → Every render [] → Only once [deps] → When dependencies change ⚠️ Common Mistake Forgetting dependencies can lead to: Stale data Unexpected bugs 👉 Always trust (and understand!) the dependency array. 🚀 Final Thought Mastering useEffect dependencies is the key to writing predictable and efficient React code. Once you get this right, everything starts making sense 🙌 #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #CodingTips
To view or add a comment, sign in
-
𝐀𝐫𝐞 𝐲𝐨𝐮 𝐬𝐭𝐢𝐥𝐥 𝐥𝐞𝐭𝐭𝐢𝐧𝐠 `useEffect` 𝐫𝐞-𝐫𝐮𝐧 𝐲𝐨𝐮𝐫 𝐞𝐱𝐩𝐞𝐧𝐬𝐢𝐯𝐞 𝐥𝐨𝐠𝐢𝐜 𝐟𝐨𝐫 𝐧𝐨 𝐠𝐨𝐨𝐝 𝐫𝐞𝐚𝐬𝐨𝐧? 🤯 It’s a common scenario: you have a `useEffect` that sets up a subscription or an interval, and you really only want it to run once on mount and clean up on unmount. So you put an empty dependency array `[]`. But what happens when you need a reference to a mutable value (like a prop or state) inside that effect, but you don't want changes to that value to re-trigger the effect? If you add it to the dependency array, it re-runs. If you omit it, you risk stale closures. Enter `useRef` as your stable escape hatch! Instead of: ```typescript useEffect(() => { const handler = () => console.log(someProp); // someProp is stale window.addEventListener('scroll', handler); return () => window.removeEventListener('scroll', handler); }, []); // Empty deps, but `someProp` is captured at mount ``` Try this pattern: ```typescript const latestSomeProp = useRef(someProp); useEffect(() => { latestSomeProp.current = someProp; // Update the ref on every render const handler = () => console.log(latestSomeProp.current); // Always fresh! window.addEventListener('scroll', handler); return () => window.removeEventListener('scroll', handler); }, []); // Effect itself only runs once ``` This way, your `useEffect` only runs once for setup/teardown, but `latestSomeProp.current` always holds the most up-to-date value. It’s perfect for ensuring cleanup functions always operate on the current state or props, without re-triggering the effect. It's a subtle but powerful pattern for optimizing performance and avoiding tricky bugs in React. What other `useEffect` patterns have saved you from debugging hell? Share your tips! #React #FrontendDevelopment #JavaScript #WebDev #Performance
To view or add a comment, sign in
-
Most React devs copy-paste the same logic across 10 components. Custom Hooks exist so you never have to. Here's what changed when I started writing my own hooks: Before custom hooks: ->useEffect + useState duplicated everywhere ->Data fetching logic scattered across files ->Business logic tangled inside UI components ->Testing was a nightmare After custom hooks: ->One useFetch handles all API calls ->One useLocalStorage replaces 20 lines of boilerplate ->Logic lives in one place, tested once, reused everywhere The rule I follow: If you write the same 3+ lines of hook logic twice — extract it. Custom hooks aren't just about reuse. They're about intent. A component that calls useUserPermissions() is infinitely more readable than one drowning in raw useEffect and useState calls. Start with these 3 hooks every project needs: 🔹 useFetch(url) — data fetching with loading + error state 🔹 useDebounce(value, delay) — debounce any input 🔹 useLocalStorage(key, default) — persistent state in one line Once you build your own hook library, you'll wonder how you ever shipped without it. 💬 What's the most useful custom hook you've ever written? Share it below — let's build a list 👇 #ReactJS #CustomHooks #Frontend #JavaScript #WebDevelopment #React #CleanCode #Programming #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Day 30 - 💡 JavaScript Tricky Question Explanation const arr = [4, 10, 2, 8]; const result = arr.find(num => num > 5) + arr.findIndex(num => num > 5); console.log(result); 👉 Output: 11 👉 Explanation: * find() returns the first value > 5 → `10` * findIndex() returns its index → `1` * Final result → `10 + 1 = 11` ⚡ Both stop at the **first match** #JavaScript #WebDevelopment #Frontend #CodingInterview #JSConcepts
To view or add a comment, sign in
-
🚀 Day 23 - Poll answer & Explanation 💡 **JavaScript Event Loop Explained (Simple & Clear)** ```javascript console.log('S'); Promise.resolve().then(() => console.log('P1')); setTimeout(() => console.log('T1'), 0); Promise.resolve().then(() => console.log('P2')); setTimeout(() => console.log('T2'), 0); console.log('E'); Output: S E P1 P2 T1 T2 ``` 🔹 **Explanation:** * `S` and `E` run first → synchronous code (call stack) * `P1`, `P2` → microtasks (Promises) → run next * `T1`, `T2` → macrotasks (setTimeout) → run last 👉 Microtasks always execute before macrotasks in the event loop. #JavaScript #ReactJS #WebDevelopment #Coding #FrontendDeveloper #InterviewPrep
To view or add a comment, sign in
-
🚀 Understanding JavaScript’s Event Loop Take a look at this seemingly simple code snippet… but the output might surprise you 👇 console.log(1); setTimeout(() => console.log(2), 0); Promise.resolve().then(() => console.log(3)); async function myFunc() { console.log(4); await Promise.resolve(); console.log(5); } myFunc(); console.log(6); 💡 Output: 1 4 6 3 5 2 🧠 What’s really happening? This is a perfect example of how JavaScript’s Event Loop works — specifically the interaction between: Call Stack (Synchronous code) Microtask Queue (Promises, async/await) Macrotask Queue (setTimeout, setInterval) 🔍 Step-by-step breakdown: ✅ 1. Synchronous execution (Call Stack first): console.log(1) → prints 1 myFunc() runs: console.log(4) → prints 4 await pauses execution → rest goes to microtask queue console.log(6) → prints 6 👉 At this point: 1 4 6 ⚡ 2. Microtasks (Higher priority): Promise.then() → prints 3 Resume async/await → prints **5` 👉 Now: 1 4 6 3 5 ⏳ 3. Macrotasks (Lowest priority): setTimeout(..., 0) → prints **2` 👉 Final output: 1 4 6 3 5 2 🎯 Key Takeaways: ✔️ async/await is just syntactic sugar over Promises ✔️ Microtasks always execute before macrotasks ✔️ setTimeout(fn, 0) does NOT mean “run immediately” ✔️ Understanding the event loop is crucial for debugging async behavior 🔥 Pro Tip: If you ever feel confused about async execution, just remember: 👉 “Sync → Microtasks → Macrotasks” #JavaScript #WebDevelopment #AsyncJS #EventLoop #Frontend #ProgrammingTips #reactjs #nodejs
To view or add a comment, sign in
-
-
"JS Fundamentals Series #4: Closures & First-Class Functions" Ever wondered how a function remembers variables even after its parent has finished executing? That's the magic of Closures - one of the most powerful concepts in JavaScript. 👉 Closures: A closure is formed when a function remembers the variables from its lexical environment, even after the outer function has returned. 👉 First-Class Functions: In JavaScript, functions are treated like any other value - they can be assigned to variables, passed as arguments, or returned from other functions 🔹Explanation - Closures combines a function with its surrounding scope. - They allow data privacy and state retention. - First-class functions make higher-order functions possible (functions that take or return another functions). 🔹 Example function outer() { let count = 0; return function inner() { count++; return count; } } const counter = outer(); console.log(counter()); // 1 console.log(counter()); // 2 Here, inner() remembers count even after outer() has finished — that’s a closure in action. 🔹Why It Matters - Enables powerful patterns like currying, memoization, and event handling. - Helps write modular, reusable, and maintainable code. - Essential for understanding modern frameworks like React. 💡 Takeaway: Closures aren’t just theory — they’re the backbone of how JavaScript manages state and builds advanced patterns. #JavaScript #WebDevelopment #Frontend #ReactJS #CodingTips #DeveloperCommunity #NamasteJS #LearningJourney #TechExplained #CareerGrowth "Closures: Functions carry their lexical environment with them 👇"
To view or add a comment, sign in
-
-
🚀 💡 JavaScript Tricky Question Explanation const arr = [4, 10, 2, 8]; const result = arr.find(num => num > 5) + arr.findIndex(num => num > 5); console.log(result); 👉 Output: 11 👉 Explanation: * find() returns the first value > 5 → `10` * findIndex() returns its index → `1` * Final result → `10 + 1 = 11` ⚡ Both stop at the **first match** #JavaScript #WebDevelopment #Frontend #CodingInterview #JSConcepts
To view or add a comment, sign in
-
⚛️ React Concept: useEffect Explained Simply The "useEffect" hook lets you handle side effects in functional components — like API calls, subscriptions, and DOM updates. 🔹 It runs after the component renders 🔹 You can control when it runs using the dependency array Basic syntax: useEffect(() => { // side effect logic return () => { // cleanup logic (optional) }; }, [dependencies]); 📌 Common use cases: • Fetching data from APIs • Adding event listeners • Handling timers 📌 Best Practice: Always define dependencies correctly and use cleanup functions to avoid memory leaks. #reactjs #frontenddevelopment #javascript #webdevelopment #softwareengineering
To view or add a comment, sign in
-
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