React Batching = 1 render. Before React 18 (React 17 & earlier) React only auto-batched state updates inside React event handlers (like onClick, onChange). Multiple setState calls in the same handler = 1 re-render so that is great for these usages. But on the other hand => (setTimeout / setInterval , Promise.then / async await,addEventListener and useEffect callbacks somtimes) React doesn't patching all in one render and Each setState triggered a separate re-render and the result be unnecessary renders that cause wasted CPU and laggy lists, forms, loaders, modals, etc. Started from React 18 everything has changed with (createRoot) 1-Automatic batching now happens almost everywhere! 2-All updates in the same event loop / microtask get grouped once for single re-render. Examples: // Click handler (always batched, even before) const handleClick = () => { setCount(c => c + 1); setLoading(true); // 1 render (same as before) }; // Async fetch – previously 2 renders, now 1! const handleFetch = async () => { const data = await fetchData(); setData(data); setLoading(false); // 1 render in React 18 }; // setTimeout – previously 2 renders, now 1! setTimeout(() => { setCount(c => c + 1); setFlag(true); }, 0); // 1 render that is okay but what if we have a case that need to separate the renders then we need to use flushSync from 'react-dom' and wrap the state with it to ensure separated renders. Example: flushSync(() => { setCount(c => c + 1); }); Hope it was helpful! #React #React18 #JavaScript #Frontend #WebDev #Performance #ReactJS #FrontendDevelopment
React 18 Batching: What's Changed and How to Optimize
More Relevant Posts
-
𝗥𝗲𝗮𝗰𝘁 𝗸𝗲𝘆𝘀: 𝗶𝗻𝗱𝗲𝘅 𝘄𝗼𝗿𝗸𝘀… 𝘂𝗻𝘁𝗶𝗹 𝗶𝘁 𝗱𝗼𝗲𝘀𝗻’𝘁. A lot of weird UI bugs in production come from this: ❌ Problem: ``` items.map((item, index) => <Row key={index} />) ``` React doesn’t track list items by “data”. It tracks component identity using keys and reuses DOM/state based on that reference. So when you: • sort • filter • insert • delete the index changes, and React reuses the wrong DOM/state. Result: • inputs swap values • checkbox state mismatches • selected item jumps • animations glitch ✅ Fix: ``` items.map((item) => <Row key={item.id} />) ``` Rule: If the order can change → keys must be stable. Have you ever debugged this bug and later found it was the key? 👀 #ReactJS #Frontend #JavaScript #WebDev #Nextjs
To view or add a comment, sign in
-
-
🤔 Ever been confused why Promise.then() runs before setTimeout(..., 0)… even though the timeout is “0ms”? That’s microtasks vs macrotasks. 🧠 JavaScript interview question What’s the difference between a microtask and a macrotask, and how does the event loop order them? ✅ Short answer Macrotasks = the “main queue” jobs (timers, events, I/O callbacks) Microtasks = “right-after-this” jobs (Promises, queueMicrotask) After a macrotask finishes, the engine drains ALL microtasks before moving on (and before painting) 🔍 A bit more detail Think of each event loop turn like this: Run one macrotask (e.g. click handler, setTimeout callback) Run all pending microtasks (and if microtasks schedule more microtasks, keep going) Browser can render/paint Next macrotask So microtasks have higher priority than timers. 💻 Example (the classic “wait… why?!”) console.log("start"); setTimeout(() => console.log("timer"), 0); Promise.resolve().then(() => console.log("promise")); console.log("end"); Output: start end promise timer Because: setTimeout schedules a macrotask then() schedules a microtask microtasks run before the next macrotask ⚠️ Small but important Microtasks are powerful… but dangerous if abused. If you keep queuing microtasks in a loop, you can starve rendering and make the UI feel frozen. ⚛️ React tie-in This is why you’ll sometimes see UI not update “immediately” when you chain a lot of Promise work. The browser can’t paint until the microtask queue is done, so heavy microtask chains can make rendering feel delayed. #javascript #webdev #frontend #reactjs #nodejs #eventloop #async #promises #performance #softwareengineering
To view or add a comment, sign in
-
#WebDevSaturdays [React Insight #2] ⚛️🧠 Most developers learn about 𝗸𝗲𝘆 through a warning message. Add one so React can track list items. Done. But keys are not just hints. they define component identity. When React renders, it compares previous and next trees. If two elements share the same key, React assumes they represent the same instance. State is preserved. Effects remain mounted. DOM nodes stay in place. Change the key, and React treats it as a completely different component. The old one unmounts. a new one mounts. This behavior is powerful when used intentionally. For example, resetting a form after submission can be done instantly by changing its key. No manual state clearing needed. But accidental key changes can cause confusing bugs. Inputs lose focus. animations restart. scroll positions reset. Where developers get surprised. 1️⃣ Using array indexes as keys in dynamic lists. 2️⃣ Deriving keys from values that change often. 3️⃣ Recreating keys inside render functions. React does not preserve components. 𝘪𝘵 𝘱𝘳𝘦𝘴𝘦𝘳𝘷𝘦𝘴 𝘪𝘥𝘦𝘯𝘵𝘪𝘵𝘪𝘦𝘴. perceived updates depend on stable identity, not rerenders. Next time state disappears unexpectedly, ask yourself. did React rerender. or did it remount. #React #WebDev #Frontend #JavaScript #DevTips
To view or add a comment, sign in
-
In ⚛️ React, Props (Properties) are used to pass data from one component to another — making components reusable and dynamic. 📌 Basic Structure of Props: ✔️ Props are passed from Parent to Child component ✔️ Props are read-only (immutable) ✔️ Data flows in a single direction (One-way data binding) 🚀 Props help build reusable, maintainable, and scalable UI components. #ReactJS #WebDevelopment #Frontend #JavaScript #LearningJourneyIn
To view or add a comment, sign in
-
-
React Hooks didn’t just change syntax — they changed how we design UI systems. ⚙️🧠 Before hooks, stateful logic lived in class components, and “reuse” often meant HOCs, render props, and tangled lifecycles. Hooks made component logic composable again: small pieces of behavior you can share, test, and reason about. Why they matter in real projects 👇 ✅ Clearer mental model: state + effects are explicit. No hidden lifecycle edge cases. ✅ Reuse without wrappers: custom hooks turn messy cross-cutting concerns (auth, caching, analytics, feature flags) into clean APIs. ✅ Better performance control: useMemo/useCallback aren’t “speed buttons” — they’re tools to stabilize references for expensive computations and child renders. ✅ Fits modern frameworks: Next.js + React Server Components push more work to the server, but hooks still define predictable client boundaries (“use client”) and interactive behavior. Practical takeaway: treat useEffect as integration glue, not a default. If derived state can be computed during render, don’t store it. If an effect exists, ask: “what external system am I syncing with?” 🔌 What’s the hook pattern you rely on most in production? 👀 #react #javascript #nextjs #frontend #webdev #softwareengineering
To view or add a comment, sign in
-
-
🚀 Day 8 Not Just Motivation — Real Concepts to Build Strong Technical Understanding (Part 8) Why does JavaScript remember variables even after a function finishes? The answer is Closure. Let’s understand this using a real-world example from React: useState. A simplified mental model of useState (conceptual) function useState(initialValue) { let state = initialValue; function setState(newValue) { state = newValue; render(); // re-render component } return [state, setState]; } Here, setState is a closure. It remembers state even after useState finishes execution. Example: Counter Component function Counter() { const [count, setCount] = React.useState(0); return ( <button onClick={() => setCount(count + 1)}> Count: {count} </button> ); } Every render is a new function call. So how does React remember count? Let’s go step by step. Render 1 – Initial Mount 1. React calls the component: Counter(). 2. useState(0) runs and creates a state slot outside the function (heap/fiber). 3. count is set to 0 and setCount is returned as a closure. 4. JSX is rendered and UI shows Count: 0. User Clicks the Button 1. Browser triggers a click event. 2. React handles the event via its synthetic event system. 3. setCount(count + 1) is called. 4. React updates internal state and schedules a re-render. Render 2 – After State Update 1. Counter() runs again. 2. Local variables are recreated, but state is preserved. 3. useState does not reinitialize; it reads existing state from memory. 4. count is now 1 and UI updates accordingly. Final Takeaway The component function re-runs on every render, but state survives because React stores it outside the function. setState works because it is a closure pointing to that preserved state. Closures are the reason useState works. #javascript #closure #reactjs #reacthooks #frontend #webdevelopment
To view or add a comment, sign in
-
Stop treating the JavaScript Event Loop like "Async Magic." Most of us use async/await, Promises, and setTimeout daily. Yet, we still encounter "mysterious" UI freezes and wonder why our code isn’t behaving as expected. The hard truth? Async code does NOT mean non-blocking UI. The browser doesn’t run your async code in parallel; it’s a single-threaded orchestrator scheduling work in a specific order. If you don't understand this order, you're likely writing bugs you can't see. The Hierarchy of Operations: 1. Call Stack: Your synchronous code always goes first. 2. Microtasks: Promises and async/await move to the front of the line. 3. Rendering: The browser attempts to update the UI. 4. Macrotasks: setTimeout and DOM events wait for all other tasks to finish. Three Common Misconceptions that Kill Performance: - "Async code is non-blocking." Wrapping a heavy for-loop in an async function doesn't make it faster; it still runs on the main thread. Heavy tasks will freeze the UI. - "setTimeout(fn, 0) is immediate." It’s not. It’s a way of saying, "I’ll wait until the stack is clear AND the browser has had a chance to render." It yields control, not speed. - "Promises are always safe." Microtasks (Promises) can "starve" the rendering process. The event loop processes the entire microtask queue before moving to rendering, which can lock your UI indefinitely. The Bottom Line: Frameworks like React, Angular, and Vue are not magic; they efficiently manage these queues. If your animations are lagging or your clicks feel unresponsive, examine your execution order rather than just your logic. The Golden Rule: Good frontend engineers write code that works. Great ones understand when the browser is allowed to breathe. #JavaScript #WebDevelopment #Frontend #WebPerformance #SoftwareEngineering #CodingTips
To view or add a comment, sign in
-
-
Server-driven UI libraries like #htmx, #Hotwire, and #Livewire are growing because they keep web development simple. Instead of sending #JSON and managing heavy frontend state, the server sends #HTML directly with minimal JavaScript. Compared to large frameworks like #React or #Angular, these libraries work best for admin panels, #dashboards, and form-based apps, where full #SPA complexity isn’t needed. Sometimes, simpler tools are the better choice. #webdevelopment #frontend #backend #fullstack #javascript
To view or add a comment, sign in
-
-
Simple React HOC Example Day8 🚀 React Tip: Higher-Order Component (HOC) Made Easy HOC = A function that takes a component and gives it extra features. Example: Button Click Counter import React, { useState } from "react"; // HOC to add counter const withCounter = (Component) => { return (props) => { const [count, setCount] = useState(0); return <Component count={count} increment={() => setCount(count + 1)} {...props} />; }; }; // Normal Button const LikeButton = ({ count, increment }) => ( <button onClick={increment}>👍 Likes: {count}</button> ); // Wrapped Button export default withCounter(LikeButton); ✅ Result: Button counts clicks automatically Logic reusable for other buttons No code repetition 💡 HOCs are useful for: Authentication 🔐 Error handling ❌ Reusable logic like counters or loaders 📈 #ReactJS #WebDevelopment #JavaScript #Frontend #ReactHOC
To view or add a comment, sign in
-
𝐀𝐫𝐞 𝐲𝐨𝐮 𝐬𝐭𝐢𝐥𝐥 𝐨𝐧𝐥𝐲 𝐮𝐬𝐢𝐧𝐠 𝐮𝐬𝐞𝐑𝐞𝐟 𝐟𝐨𝐫 𝐃𝐎𝐌 𝐞𝐥𝐞𝐦𝐞𝐧𝐭𝐬? 𝐘𝐨𝐮'𝐫𝐞 𝐦𝐢𝐬𝐬𝐢𝐧𝐠 𝐚 𝐭𝐫𝐢𝐜𝐤 𝐟𝐨𝐫 𝐩𝐞𝐫𝐟𝐨𝐫𝐦𝐚𝐧𝐜𝐞. Many devs reach for `useState` every time they need to persist a value between renders. But if that value doesn't need to trigger a re-render when it changes, `useState` is overkill and can cause unnecessary work. This is where `useRef` shines beyond just ref attributes on JSX. It's a mutable object (current property) that persists across renders, but updates to its value don't trigger a re-render. Example: ```javascript function Timer() { const intervalRef = useRef(null); // Not for a DOM element! useEffect(() => { intervalRef.current = setInterval(() => { // do something without triggering re-render console.log('Timer running...'); }, 1000); return () => clearInterval(intervalRef.current); }, []); // ... other component logic } ``` In this scenario, intervalRef holds the `setInterval` ID. We need it to be consistent across renders and cleaned up on unmount, but changing the ID itself doesn't require the component to re-render. Using `useState` here would be less efficient. Think of `useRef` for any mutable value you need to "store" in your component's lifecycle without affecting the UI's render cycle directly. It's fantastic for timers, previous values, or expensive computations you only want to run once. How are you leveraging `useRef` in your React applications? Share your performance hacks! #React #Frontend #Performance #JavaScript #WebDev
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