🧠 Is setState 𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 or 𝗮𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 in React? Short answer 👉 setState is 𝗮𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 — by design. React doesn’t update state immediately. Instead, it schedules state updates and batches multiple updates together to avoid unnecessary re-renders and improve performance. 𝘌𝘹𝘢𝘮𝘱𝘭𝘦:– setCount(count + 1); console.log(count); 𝘖𝘶𝘵𝘱𝘶𝘵:- 0 𝗪𝗵𝘆? Because setState does not update the value instantly — the current render still holds the old state. 🔁 𝗕𝗮𝘁𝗰𝗵𝗶𝗻𝗴 𝗶𝗻 𝗮𝗰𝘁𝗶𝗼𝗻 setCount(count + 1); setCount(count + 1); 𝗥𝗲𝘀𝘂𝗹𝘁 👉 1 (not 2) Both updates read the same stale state, and React batches them into a single render. ✅ The correct pattern (when state depends on previous state) setCount(prev => prev + 1); setCount(prev => prev + 1); 𝗥𝗲𝘀𝘂𝗹𝘁: 2 This works because React provides the latest queued state to each update. 🧠 𝗞𝗲𝘆 𝘁𝗮𝗸𝗲𝗮𝘄𝗮𝘆 setState doesn’t change state immediately. It requests a state change — React decides when to apply it. This behavior enables better performance, smoother UI, and concurrent rendering. 👀 𝗕𝘂𝘁 𝗵𝗲𝗿𝗲’𝘀 𝘁𝗵𝗲 𝘁𝘄𝗶𝘀𝘁... 👉 setState can be synchronous in React — but only in very specific situations and for a specific purpose. I’ll cover when, why, and whether you should ever use it in my next post. Stay tuned 🚀 #ReactJS #JavaScript #Frontend #WebDevelopment #ReactHooks #Performance #SoftwareEngineering
React setState behavior: async or sync?
More Relevant Posts
-
🚀 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
-
You don’t really “know React” until you can build the basics Buttons. Inputs. Selects. Dropdowns. We use them every day — yet many developers treat them as black boxes from a UI library. Knowing how to build these components from scratch matters more than it looks: - You understand accessibility (keyboard navigation, focus states, ARIA) - You design clear APIs (props, variants, controlled vs uncontrolled) - You handle edge cases (loading, disabled, error, async behavior) - You avoid over-engineering and leaky abstractions - You customize behavior instead of fighting a library UI libraries are great. They save time. They reduce bugs. But when something breaks, needs customization, or doesn’t exist yet, fundamentals are what save you. If you can confidently build a button, you can build a design system. If you can build a dropdown, you understand state, events, and composition. Frameworks change. Libraries come and go. Well-built components are forever. #React #Frontend #WebDevelopment #JavaScript #UI #DesignSystems
To view or add a comment, sign in
-
-
🚀 Day 64 Conditional Rendering in React (4 Powerful Patterns) Today I learned how Conditional Rendering works in React — a core concept that decides what appears on the UI based on a condition. 🔹 What is Conditional Rendering? Conditional rendering means showing different UI elements depending on state or props. Examples: • If age ≥ 18 → show “Can Vote” • If user is logged in → show Logout • Else → show Login • This is how React creates dynamic user experiences. 🔹 4 Ways to Do Conditional Rendering in React 1️⃣ If–Else Statement Best for complex logic with multiple conditions. if (isLoggedIn) { return <Logout />; } else { return <Login />; } 2️⃣ Ternary Operator Clean and concise for simple two-way conditions. • isLoggedIn ? <Logout /> : <Login /> 3️⃣ Logical AND (&&) Operator Render something only if condition is true. • isLoggedIn && <Logout /> 4️⃣ Early Return Pattern Handle edge cases first and keep code clean. if (!isLoggedIn) return <Login />; return <Logout />; 🔹 What Was Implemented • Created isLoggedIn state using useState • Built simple Login and Logout button components • Switched UI dynamically using all four methods • Compared readability and use cases of each approach 📌 Key Takeaways • Conditional rendering drives dynamic UIs • Choose syntax based on readability & complexity • && is great when there’s no else case • Early returns reduce nesting and improve clarity 🧠 Quick Comparison MethodBest ForIf-ElseComplex conditionsTernarySimple true/false UILogical &&Conditional display onlyEarly ReturnClean, readable components Mastering these patterns makes React components cleaner, smarter, and more scalable 💡 On to more mini-projects next! 🚀 #ReactJS #JavaScript #FrontendDevelopment #LearningInPublic #WebDevelopment #Day64
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
-
-
⚛️ This small design decision makes modern UIs feel smooth. React doesn’t update the DOM directly. And honestly… that’s a good thing. Instead, it creates something called the Virtual DOM — a lightweight copy of the real DOM living in memory. When the state changes, React doesn’t panic. It compares the old Virtual DOM with the new one, finds the difference, and updates only what actually changed. No full reload. No unnecessary updates. The DOM isn’t fast. React is just smart about touching it.🧠 That small design decision is what makes modern UIs feel smooth. #ReactJS #FrontendDevelopment #JavaScript #SoftwareEngineering #WebDevelopment
To view or add a comment, sign in
-
Topic: React Performance Optimization – What Actually Matters ⚡ React Performance Optimization – What Actually Matters Before adding useMemo, useCallback, or fancy libraries… ask yourself one question: Is there really a performance problem? Here’s what actually makes the biggest impact 👇 🔹 Split Components Properly Smaller components = fewer re-renders. 🔹 Avoid Unnecessary State Less state → less complexity → better performance. 🔹 Use Keys Correctly in Lists Wrong keys cause UI bugs + wasted re-renders. 🔹 Understand Re-renders Re-render ≠ DOM update (React is already optimized). 🔹 Measure Before Optimizing Use React DevTools Profiler, not guesswork. 💡 Hard Truth Most performance issues come from bad architecture, not missing hooks. 📌 Golden Rule Optimize when needed, not by default. 📸 Daily React tips & visuals: 👉 https://lnkd.in/g7QgUPWX 💬 What was the real cause of your last performance issue? 👍 Like | 🔁 Repost | 💭 Comment #React #ReactPerformance #FrontendDevelopment #JavaScript #WebDevelopment #ReactJS #DeveloperLife
To view or add a comment, sign in
-
I just finished Frontend Masters “A Tour of JavaScript & React Patterns” and the biggest mindset shift for me was this: Most React “performance problems” are actually rendering problems. Not “React is slow”, but “I accidentally made more of the tree render than needed”. A few things I’m taking away and actively applying: ✅ Context is not a state manager It is a delivery mechanism. If the value changes often, it becomes a re-render broadcaster. That is perfect for “rarely changes” state (theme, locale, auth), risky for high frequency state. ✅ The fastest component is the one that does not re-render Before reaching for memo everywhere, I ask: Can I move state down? Can I split the provider? Can I pass a stable callback? Can I avoid creating new objects in props? ✅ Render cost is usually in the children Even small parent changes can re-render expensive lists, charts, tables. Splitting components and isolating heavy parts pays off more than micro-optimizing one hook. ✅ Patterns are about shaping render boundaries Custom hooks, compound components, provider splitting, controlled vs uncontrolled components. These are not just “clean code” choices. They decide how much UI updates when data changes. And a big one outside the component tree: ✅ Performance starts before React even runs Choosing the right rendering strategy changes the whole user experience: CSR when you need app-like interactivity and data is truly user-specific SSR when you need fast first paint plus fresh data per request SSG when content is stable and you want maximum speed ISR when you want SSG speed but still keep content reasonably fresh without rebuilding everything Simple rule I like now: Architecture is often performance in disguise, both in your component tree and in your rendering strategy. #react #nextjs #javascript #performance #frontend #webdevelopment #softwareengineering
To view or add a comment, sign in
-
-
🚀 How React’s Virtual DOM Works (Simple Explanation) Ever wondered how React updates the UI so fast? The magic lies in the Virtual DOM 🧠 What is the Virtual DOM? It’s a lightweight JavaScript representation of the real DOM. Instead of directly updating the browser DOM (which is slow), React works with this virtual copy. ⚙️ How it works step by step: 1️⃣ State or Props Change When state or props change, React creates a new Virtual DOM tree. 2️⃣ Diffing Algorithm React compares the new Virtual DOM with the previous one (this process is called diffing). 3️⃣ Find the Minimum Changes React figures out exactly *what* changed — not the whole UI, just the affected parts. 4️⃣ Efficient DOM Update Only those minimal changes are applied to the **real DOM**, making updates fast and efficient. ⚡ Why this matters * Faster UI updates * Better performance * Predictable rendering * Great developer experience 💡 In short: > React doesn’t update everything. It updates *only what’s necessary.* If you’re building scalable and performant frontend apps, understanding the Virtual DOM is a must! #ReactJS #VirtualDOM #FrontendDevelopment #JavaScript #WebDevelopment #ReactTips
To view or add a comment, sign in
-
-
🧠 How Browsers Actually Work (What Every Frontend Dev Should Know) When you hit Enter after typing a URL, the browser doesn’t “open a page”… it builds one from scratch. 🔹 Step 1: Finding the Server (DNS) Browser converts the domain into an IP address so it knows where to talk. 🔹 Step 2: Fetching Resources An HTTP request is sent → server responds with HTML, CSS, JS, fonts, images. 🔹 Step 3: Building the Page HTML → DOM CSS → CSSOM DOM + CSSOM → Render Tree Then comes Layout (sizes & positions) and Paint (pixels on screen). 🔹 Step 4: JavaScript Takes Control JS runs in the browser engine, can block rendering, manipulate the DOM, attach events, and call APIs. 🔹 Step 5: The Event Loop Handles async tasks (callbacks, promises, timers) so heavy JS doesn’t freeze the UI. 💡 Why this matters If you understand this flow, you automatically write: Faster UIs Fewer re-renders Better loading strategies Cleaner React / Next.js apps 👉 Browsers are rendering engines + JS runtimes + networking layers, not just viewers. If frontend is your craft—browser internals are your foundation 🚀 #FrontendEngineering #JavaScript #WebPerformance #ReactJS #NextJS
To view or add a comment, sign in
-
Ever wonder what makes React so fast and smooth, even when handling complex UIs? Let’s look under the hood at React Fiber. Before React 16, React used the "Stack Reconciler." It worked synchronously, meaning once it started rendering an update, it couldn't stop until it was finished. If an update was massive, it would block the browser's main thread, leading to dropped frames and a sluggish user experience. Enter React Fiber: a complete rewrite of React’s core algorithm designed to solve this exact problem. At its core, Fiber is a reimplementation of the stack, designed for React components. You can think of a single "fiber" as a virtual stack frame representing a unit of work. Here is why Fiber was a game-changer for frontend architecture: Incremental Rendering: Instead of rendering the entire component tree in one giant, uninterruptible task, Fiber breaks the work down into smaller, manageable chunks. Time-Slicing & Prioritization: Fiber can pause, abort, or reuse work. It assigns priorities to different updates. For example, a user typing in an input field (high priority) will interrupt a massive background data render (low priority) to ensure the UI stays responsive. Two-Phase Execution: Phase 1: Render (Interruptible). React builds a "work-in-progress" tree in memory. It can pause this phase to yield control back to the browser so high-priority tasks can run. Phase 2: Commit (Synchronous). Once the render phase is complete, React commits the changes to the actual DOM all at once, ensuring the user never sees an incomplete UI. By breaking rendering into chunks and yielding to the main thread, Fiber is the invisible engine that powers React's modern Concurrent Mode features, like Suspense and useTransition. Understanding Fiber isn't just theory—it helps us write better, more performant React applications by understanding how our components are processed. Have you ever used concurrent features like useTransition or useDeferredValue to optimize a heavy UI? #ReactJS #FrontendDevelopment #WebPerformance #JavaScript #SoftwareEngineering #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