🚀 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
More Relevant Posts
-
Why React is Still Insanely Powerful in 2026 After working extensively with React, I’ve come to appreciate that React isn’t just a UI library — it’s a highly optimized rendering engine built with some brilliant architectural decisions. Here are some things that make React incredibly powerful: ⚡ 1. Diffing Algorithm — From O(n³) → O(n) Comparing two UI trees normally takes O(n³) time. React optimized this to O(n) using: • Element type comparison • Stable keys This is why React can efficiently update even large, complex applications. 🧠 2. Updates are Scheduled, Not Immediate When you call :- setState() React doesn’t immediately update the DOM. Instead, it: • Queues updates • Batches multiple updates together • Optimizes when and how rendering happens Result → Fewer DOM operations and better performance. 🧵 3. React Fiber Architecture React Fiber introduced the ability to: • Pause rendering • Resume rendering • Prioritize critical updates This allows React to keep the UI responsive even during heavy rendering. 🔄 4. Re-render ≠ DOM Update A component re-render doesn’t always mean the DOM changes. React first compares changes in the Virtual DOM and updates only what is necessary. This selective update approach makes React extremely efficient. 🎯 5. Prioritized Rendering React prioritizes user interactions like clicks and typing over non-critical updates. This ensures smooth and responsive user experiences. 🧩 6. Separate Render and Commit Phases React works in two phases: Render Phase → Calculates what changed Commit Phase → Applies changes to the DOM This separation enables better control and optimization. React is not just rendering components. It’s managing scheduling, reconciliation, and efficient UI updates behind the scenes. Understanding these internals completely changes how you think about building React applications. #React #Frontend #JavaScript #SoftwareEngineering #WebDevelopment #ReactJS #Programming #FrontendDeveloper
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
-
-
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
-
-
How JavaScript Async Keeps Your UI Smooth - A Visual Story As frontend engineers, we know JavaScript is single-threaded. That means any heavy synchronous code can block the main thread, freezing the UI, causing scrolling stutters, clicks to lag, and animations to drop frames. Here’s how async mechanisms help us maintain a fluid experience: 1. Synchronous code runs first (everything in the call stack). 2. Microtasks (Promise.then(), MutationObserver) run immediately after the current stack clears. 3. Macrotasks (setTimeout, setInterval, I/O events) run next in the event loop. Pro tips for a smooth UI: 1. Offload heavy computations to Web Workers → keeps the main thread free. 2. Chunk long tasks using requestIdleCallback or setTimeout → allow the browser to paint frames. 3. Use async APIs for network calls, animations (requestAnimationFrame), and non-blocking updates. The result: fluid scrolling, responsive interactions, seamless animations. Understanding the event loop and async flow is key to building performant, user-friendly apps. What’s your favorite trick to keep complex UIs smooth in production apps? #JavaScript #Frontend #EventLoop #Async #WebPerformance #UIUX #SeniorFrontend #WebDev
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
-
-
Here’s how you can build clean, reusable components by leveraging styled-components in React One common challenge many frontend developers face is managing UI components as projects grow. At the beginning, everything feels simple. But over time, you start to see problems like: Too many duplicated buttons Inconsistent styles Hard-to-maintain CSS files Rewriting the same components again and again This is where reusable components + styled-components become very powerful. Recently, I implemented a reusable Button system where: I created a BaseButton Extended it into GoogleSignInButton and InvertedButton Used a helper function to dynamically select the right button based on props With this approach, I only pass a buttonType, and the correct styled button is rendered automatically. Example from my implementation: const getButton = (buttonType) => ({ base: BaseButton, google: GoogleSignInButton, inverted: InvertedButton, }[buttonType]); This allows me to reuse one Button component across the entire application while keeping the styles organized and consistent. Benefits of this approach: Cleaner codebase Better scalability Consistent UI Easier maintenance Faster development Instead of building new buttons every time, I now focus more on functionality and user experience. Still learning, building, and improving every day. Would love to hear how You handle component reusability in Your projects. #ReactJS #FrontendDevelopment #StyledComponents #JavaScript #WebDev #TechGrowth
To view or add a comment, sign in
-
-
🎯 Most Developers Use React — But Misunderstand What “Render” Actually Means A lot of React confusion starts with one overloaded word: render. People hear “render” and imagine the browser instantly repainting the screen every time something runs. That’s not what React rendering really means. Here’s the clean mental model — in under a minute 👇 When React renders a component, it is mainly doing this: ➡ Reading your component function ➡ Executing the JSX logic ➡ Producing a new UI description ➡ Comparing it with the previous one ➡ Updating only the changed parts in the real DOM Rendering is a calculation step first — not a direct DOM update. Also, render is not a one-time event. It happens multiple times during a component’s lifecycle: ✅ First time component appears → Initial render (mount) ✅ When state changes → Re-render ✅ When props change → Re-render ✅ When parent re-renders → Child may re-render Important distinction: Mount = first render Update = every render after that Another key point many miss 👇 React does NOT blindly rewrite the entire DOM on every render. It updates a lightweight virtual tree, runs a diff, and patches only what changed. That selective update is what keeps React UIs fast and predictable. If you understand what render truly means, topics like memoization, re-renders, and performance optimization become much easier to reason about. Clarity beats memorization every time. 👉 Follow Rahul R Jain for more real interview insights, React fundamentals, and practical frontend engineering content. #ReactJS #FrontendDevelopment #ReactConcepts #VirtualDOM #ReRendering #WebDevelopment #JavaScript #FrontendEngineering #UIPerformance #ReactInterview
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
-
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