Most React devs know when to use useLayoutEffect. Almost none can explain why it behaves differently. The answer lives inside the commit phase. React's update cycle has two big stages: render (reconcile, diff, no DOM writes) and commit (apply changes, run effects). Commit itself splits into 3 sub-phases: → Before Mutation — read DOM snapshots before anything changes → Mutation — insert, update, remove DOM nodes → Layout — refs attached, useLayoutEffect fires here, synchronously useEffect never runs in the Layout pass. During reconciliation, React builds an Effect List — fiber nodes tagged with pending work. Fibers marked HookLayout flush during the Layout sub-phase. Fibers marked HookPassive get handed to the scheduler and run after the browser paints. React docs put it directly: "React guarantees that the code inside useLayoutEffect and any state updates scheduled inside it will be processed before the browser repaints the screen." Classic case where this matters: tooltip positioning. With useEffect, users catch a flicker — the tooltip renders in the wrong spot, then jumps. With useLayoutEffect, both renders complete before any pixel changes on screen. The tradeoff: useLayoutEffect blocks paint. Use it only when you need to measure or mutate the DOM before the user sees the frame. Data fetching, subscriptions, analytics — those belong in useEffect. One gotcha: useLayoutEffect is a no-op in SSR. React will warn you. Guard with typeof window !== 'undefined' or default to useEffect in universal code. #frontend #reactjs #javascript #typescript #frontenddevelopment #softwareengineering #webdevelopment
Artem Krasovskyi’s Post
More Relevant Posts
-
I just started a deep dive into React and came across how it uses snapshots to re-render the view, by strictly comparing references of the old state copy in memory to the newer one. That immediately triggered a question: When we do so many state updates in a large production app, we are essentially creating so many snapshots in memory that will most likely never be used again. What happens to all this garbage sitting in memory? There must be massive leaks everywhere, right? Short answer: No. Long answer: Here's why. Every state update creates a new snapshot in memory. The old one loses all references pointing to it. JavaScript's Garbage Collector sees this and frees it automatically. GC's only rule → if nothing points to it, it's gone. 🧹 Real leaks in React come from YOU accidentally holding references outside React's control: ❌ Pushing state into an array that lives outside the component ❌ Adding event listeners without removing them ❌ setInterval running after the component unmounts In all these cases GC sees "something still points here" and leaves it alone, forever. useEffect cleanup exists for exactly this reason: return () => window.removeEventListener("resize", handler); One line. Prevents an entire class of memory leaks. React is not the problem. Uncleaned side effects are. #React #JavaScript #Frontend #SoftwareEngineering #WebDev
To view or add a comment, sign in
-
Some of the hardest React bugs I’ve seen weren’t actually inside React. They were happening somewhere in between. Between the event loop and the render cycle. You know the kind of bug. Everything looks correct. State updates are there. Handlers are wired properly. The logic makes sense. And yet… the UI shows stale data. Something flickers for a split second. It works fine locally, but breaks under real user interaction. Those are the bugs that make you question your sanity a bit. What’s really going on is this. We tend to think of React and JavaScript as one system. But they’re not. JavaScript runs your code - sync, promises, timeouts, all of that. React runs its own process - scheduling renders, batching updates, deciding when the UI actually updates. Most of the time, we blur that into one mental model. And most of the time it works. Until it doesn’t. That gap is where things get weird. You’ve probably seen versions of this: 🔹 You call setState and immediately get the old value 🔹 A setTimeout fires and uses stale data 🔹 A promise resolves and overwrites something newer 🔹 Everything works… until a user clicks fast enough Individually, none of this is surprising. But when it happens in a real app, it feels unpredictable. Because the problem isn’t what your code does. It’s when it runs. That’s why these bugs are so frustrating. You’re not debugging logic anymore. You’re debugging timing. The more I work on complex React apps, the more I notice this - a big part of senior frontend work isn’t just knowing hooks or patterns. It’s understanding how React’s rendering model interacts with the JavaScript runtime. Because once timing gets involved what looks correct can still be completely wrong. #reactjs #javascript #frontend #webdevelopment #softwareengineering #debugging #performance #typescript
To view or add a comment, sign in
-
💡 Mastering useEffect in React — Stop Guessing, Start Understanding If you’ve worked with React, you’ve probably used useEffect… and maybe struggled with it too. Here’s the simple way to think about it: 👉 useEffect lets you run side effects in your components That means anything that interacts outside the React render cycle: - API calls 🌐 - Subscriptions 🔔 - Timers ⏱️ - DOM manipulation 🧩 🔑 The 3 most important patterns: 1] Run once (on mount): useEffect(() => { console.log("Component mounted"); }, []); 2] Run when a dependency changes: useEffect(() => { console.log("Value changed"); }, [value]); 3] Cleanup (avoid memory leaks): useEffect(() => { const timer = setInterval(() => { console.log("Running..."); }, 1000); return () => clearInterval(timer); }, []); ⚠️ Common mistakes to avoid: Forgetting dependencies → leads to stale data bugs Adding unnecessary dependencies → causes infinite loops Ignoring cleanup → memory leaks & performance issues 🧠 Pro tip: If your useEffect feels complicated… it probably is. Try splitting it into smaller effects or rethinking your logic. ✨ useEffect isn’t hard — it’s just misunderstood. Once you get the mental model right, everything clicks. #React #JavaScript #WebDevelopment #Frontend
To view or add a comment, sign in
-
🧠 Why Inline Functions Can Hurt React Performance This looks totally fine 👇 <button onClick={() => handleClick(id)}> Click </button> Works? ✅ Clean? ✅ Optimized? ❌ 🔍 What’s actually happening Every render creates a new function instance. () => handleClick(id) // new function every time So React sees: 👉 “This prop changed” Even if nothing else changed. ⚠️ The hidden impact When passed to child components: <Child onClick={() => handleClick(id)} /> 👉 Child re-renders every time 👉 React.memo becomes useless 👉 Performance drops in large apps ✅ Better approach const handleItemClick = useCallback(() => { handleClick(id); }, [id]); <Child onClick={handleItemClick} /> Now: ✔ Stable reference ✔ Fewer re-renders ✔ Better performance 🎯 Real Insight React doesn’t compare function logic. It compares references. 💥 Senior takeaway Most performance issues are not from big logic. They come from small patterns repeated many times. #ReactJS #FrontendDeveloper #JavaScript #WebDevelopment #Performance #SoftwareEngineering #CodingTips #TechCareers
To view or add a comment, sign in
-
🚀 Controlled vs Uncontrolled Components in React — Real-World Perspective Most developers learn: 👉 Controlled = React state 👉 Uncontrolled = DOM refs But in real applications… 👉 The choice impacts performance, scalability, and maintainability. 💡 Quick Recap 🔹 Controlled Components: Managed by React state Re-render on every input change 🔹 Uncontrolled Components: Managed by the DOM Accessed via refs ⚙️ The Real Problem In large forms: ❌ Controlled inputs → Too many re-renders ❌ Uncontrolled inputs → Hard to validate & manage 👉 So which one should you use? 🧠 Real-world Decision Rule 👉 Use Controlled when: ✔ You need validation ✔ UI depends on input ✔ Dynamic form logic exists 👉 Use Uncontrolled when: ✔ Performance is critical ✔ Minimal validation needed ✔ Simple forms 🔥 Performance Insight Controlled input: <input value={name} onChange={(e) => setName(e.target.value)} /> 👉 Re-renders on every keystroke Uncontrolled input: <input ref={inputRef} /> 👉 No re-render → better performance ⚠️ Advanced Problem (Most devs miss this) 👉 Large forms with 20+ fields Controlled approach: ❌ Can slow down typing 👉 Solution: ✔ Hybrid approach ✔ Use libraries (React Hook Form) 🧩 Industry Pattern Modern apps often use: 👉 Controlled logic + Uncontrolled inputs internally Example: ✔ React Hook Form ✔ Formik (optimized patterns) 🔥 Best Practices ✅ Use controlled for logic-heavy forms ✅ Use uncontrolled for performance-critical inputs ✅ Consider form libraries for scalability ❌ Don’t blindly use controlled everywhere 💬 Pro Insight (Senior Thinking) 👉 This is not about “which is better” 👉 It’s about choosing the right tool for the problem 📌 Save this post & follow for more deep frontend insights! 📅 Day 17/100 #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #PerformanceOptimization #SoftwareEngineering #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
You think this React code will increment the counter to 2? Maga Look again.👇🐘🐘🐘 function App() { const [count, setCount] = useState(0); const handleClick = () => { setTimeout(() => { setCount(count + 1); }, 1000); setCount(count + 1); }; return ( <> <p>{count}</p> <button onClick={handleClick}>Click</button> </> ); } Most developers say: 👉 “First +1 immediately, then +1 after 1 second → final = 2” ❌ Wrong 🧠 What actually happens setCount(count + 1) → updates to 1 setTimeout callback runs later… But it uses stale count = 0 (closure!) 👉 So it sets 1 again 🎯 Final Result Count = 1, not 2 🚨 The real problem This is not a React bug This is a JavaScript closure + event loop problem Functions capture old state Async callbacks don’t magically get updated values React state is snapshot-based, not live ✅ Fix setCount(prev => prev + 1); ✔ Always use functional updates when state depends on previous value ✔ Works correctly with async (timeouts, promises, events) 💡 Takeaway If your mental model is: 👉 “state updates automatically everywhere” You’ll ship bugs. If your mental model is: 👉 “state is captured at execution time” You’ll write predictable systems. This is the difference between writing code that works… and code that scales in production. USE prev maga 😍 setCount(prev => prev + 1); 🐘🐘🐘 #ReactJS #JavaScript #Frontend #WebDevelopment #Debugging #EventLoop
To view or add a comment, sign in
-
I struggled with this React concept more than I expected… 👇 👉 Why are my API calls running twice? ⚙️ What you’ll notice You open your network tab and suddenly see this: api/me → called twice api/roles → called twice api/permissions → called twice Just like in the screenshot 👇 Same request, duplicated… again and again. ⚙️ What’s actually happening In React (development mode), if your app is wrapped in Strict Mode, React will run effects twice on purpose. useEffect(() => { fetch("/api/users") .then(res => res.json()) .then(setUsers); }, []); Even though it looks like it should run once… it doesn’t (in dev). 🧠 What’s going on under the hood React basically does a quick cycle: mount → unmount → remount Why? To catch hidden side effects To check if cleanup is handled properly To make sure your logic doesn’t break on re-renders So if your API call runs twice, React is just making sure your code can handle it. 💡 The important part This only happens in development Production behaves normally (runs once) Your side effects should be safe to run multiple times 🚀 Final thought If your network tab looks “noisy” like the screenshot, it’s not React being broken — it’s React being careful. And once you understand this, debugging becomes a lot less confusing. #React #Frontend #JavaScript #WebDevelopment #ReactJS #SoftwareEngineering
To view or add a comment, sign in
-
🚀 useReducer in React — When useState is Not Enough As your React app grows… 👉 State becomes complex 👉 Multiple updates depend on each other 👉 Logic gets messy That’s where useReducer comes in. 💡 What is useReducer? useReducer is a hook for managing complex state logic using a reducer function. 👉 Inspired by Redux ⚙️ Basic Syntax const [state, dispatch] = useReducer(reducer, initialState); 🧠 How it works 👉 Instead of updating state directly: setCount(count + 1); 👉 You dispatch actions: dispatch({ type: "increment" }); 👉 Reducer decides how state changes: function reducer(state, action) { switch (action.type) { case "increment": return { count: state.count + 1 }; default: return state; } } 🧩 Real-world use cases ✔ Complex forms ✔ Multiple related states ✔ State transitions (loading → success → error) ✔ Large components with heavy logic 🔥 Why useReducer? 👉 useState works well for simple state 👉 useReducer works better for structured logic 🔥 Best Practices (Most developers miss this!) ✅ Use when state depends on previous state ✅ Use for complex or grouped state ✅ Keep reducer pure (no side effects) ❌ Don’t use for simple state ❌ Don’t mix business logic inside components ⚠️ Common Mistake // ❌ Side effects inside reducer function reducer(state, action) { fetchData(); // ❌ Wrong return state; } 👉 Reducers must be pure functions 💬 Pro Insight (Senior-Level Thinking) 👉 useState = simple updates 👉 useReducer = predictable state transitions 👉 If your state has “rules” → useReducer 📌 Save this post & follow for more deep frontend insights! 📅 Day 20/100 #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #StateManagement #SoftwareEngineering #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
Why does the same React component behave differently on each render? You wrote it once.... Same code. Same props. But sometimes: → It shows different data → It lags → It resets Looks like a bug… But often, it’s just React doing its job. 𝗛𝗲𝗿𝗲’𝘀 𝘄𝗵𝗮𝘁’𝘀 𝗮𝗰𝘁𝘂𝗮𝗹𝗹𝘆 𝗵𝗮𝗽𝗽𝗲𝗻𝗶𝗻𝗴: Every time a parent component re-renders — every child inside it re-renders too. React re-runs the component function to check what changed. Even if props look the same. 𝗛𝗼𝘄 𝘁𝗼 𝘁𝗲𝗹𝗹 𝗥𝗲𝗮𝗰𝘁 𝘁𝗼 𝘀𝗸𝗶𝗽 𝗿𝗲-𝗿𝗲𝗻𝗱𝗲𝗿: Wrap your component in React.memo() const Card = React.memo(({ name }) => { return <div>{name}</div> } Now React skips re-rendering Card unless its props actually change. Same component. Smarter behavior. 𝗥𝗲-𝗿𝗲𝗻𝗱𝗲𝗿 𝗵𝗮𝗽𝗽𝗲𝗻𝘀 𝘄𝗵𝗲𝗻: → State changes → Props change → Parent re-renders `React.memo` stops the third one (when props are stable). 𝗣𝗿𝗼 𝘁𝗶𝗽: If memo isn't skipping, check if you're passing new functions/objects/arrays every time — those break the shallow compare. Fix with 𝘶𝘴𝘦𝘊𝘢𝘭𝘭𝘣𝘢𝘤𝘬/𝘶𝘴𝘦𝘔𝘦𝘮𝘰. Understanding this is the difference between “it works” and “it scales.” Save this — next time re-renders confuse you, you’ll know exactly why. Have you ever had unexpected re-renders break your app? Drop it below 👇 Follow for more React concepts explained simply. #reactjs #webdevelopment #javascript #MERN
To view or add a comment, sign in
-
-
As a developer, I’ve noticed some small things… but they matter a lot 👨💻 1. Console Errors Even When Feature Works Sometimes our JavaScript/jQuery code works perfectly on UI… but the console still shows errors or warnings. 👉 Real examples: `undefined is not a function` but the feature still runs partially Deprecated jQuery methods showing warnings API error in console but UI shows cached/old data 💡 Lesson: Even if it “works”, ignoring console errors can create bigger issues later. --- 2. Works in Chrome, Breaks in Other Browsers We often test only in Chrome… and everything looks perfect 😄 But in other browsers or app web views, things break. 👉 Real examples: CSS flexbox/layout breaking in Safari New JS features not supported in older browsers Different font or spacing issues across browsers 💡 Lesson: A good developer doesn’t just make it work… They make it work everywhere. --- 🚀 Still learning, but these are things I’m experiencing in real projects. #JavaScript #Frontend #Debugging #LearningInPublic #DeveloperJourney #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