Why is there a random '0' on my screen?!" The classic React trap. 🪤⚛️ If you have built React apps for a while, you have probably seen a stray `0` randomly floating in your UI. This happens when we misuse conditional rendering! Keeping JSX clean means using inline expressions, but you have to choose the right tool for the job: 1️⃣𝐓𝐡𝐞 "𝐄𝐢𝐭𝐡𝐞𝐫/𝐎𝐫" (𝐓𝐞𝐫𝐧𝐚𝐫𝐲 𝐎𝐩𝐞𝐫𝐚𝐭𝐨𝐫 `? :`) 🔀 Use this when you need to choose between two different components. 𝐸𝑥𝑎𝑚𝑝𝑙𝑒: `{isLoggedIn ? <Dashboard /> : <LoginForm />}` It is basically a clean `if-else` statement right inside your UI. 2️⃣𝐓𝐡𝐞 "𝐎𝐧𝐥𝐲 𝐈𝐟" (𝐋𝐨𝐠𝐢𝐜𝐚𝐥 𝐀𝐍𝐃 `&&`) 🚪 Use this when you want to render something 𝑜𝑛𝑙𝑦 if a condition is met. If it's false, render nothing. 𝐸𝑥𝑎𝑚𝑝𝑙𝑒: `{isLoading && <Spinner />}` ⚠️ 𝐓𝐡𝐞 𝐂𝐨𝐦𝐦𝐨𝐧 𝐏𝐢𝐭𝐟𝐚𝐥𝐥 (𝐓𝐡𝐞 𝐃𝐫𝐞𝐚𝐝𝐞𝐝 '𝟎'): In JavaScript, `0` is falsy. But in React, if you put a number in JSX, React renders it! ❌ `cart.length && <CheckoutButton />` ➔ If length is 0, your UI literally prints "0". ✅ `cart.length > 0 && <CheckoutButton />` ➔ Forces a boolean check. Renders nothing if false. Swipe through the infographic below to see the visual breakdown! 👇 Be honest, how many times has the "length &&" bug caught you off guard? #ReactJS #FrontendDevelopment #WebDev #JavaScript #CleanCode #SoftwareEngineering #CodingTips
React Conditional Rendering Traps: Avoid the '0' Bug
More Relevant Posts
-
🧠 What Actually Triggers a Re-render in React? Many developers memorize hooks. But fewer understand what really causes a component to re-render. Let’s break it down 👇 Example Code : function App() { const [count, setCount] = useState(0); const memoValue = useMemo(() => { console.log("useMemo runs"); return count * 2; }, [count]); useEffect(() => { console.log("useEffect runs"); }, [count]); return ( <button onClick={() => setCount(count + 1)}> {count} </button> ); } 🔄 What Happens When You Click? 1️⃣ State updates setCount triggers a re-render. 2️⃣ Component re-runs Entire function runs again. 3️⃣ useMemo runs (if dependency changed) 4️⃣ DOM updates 5️⃣ useEffect runs (after render) 🎯 Final Order Render → useMemo → Paint → useEffect 🧠 Important Notes React re-renders when state or props change useMemo runs during render useEffect runs after render useCallback does NOT run — it only stores a function Understanding execution order is what separates React users from React engineers. #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #WebDevelopment #LearningInPublic
To view or add a comment, sign in
-
💡 React Tip: Improving Form Performance in Large Applications While working on a complex React form with 50+ fields, I noticed frequent re-renders that were impacting performance and user experience. The solution? React Hook Form instead of traditional controlled inputs. Why React Hook Form works well for large forms: ✅ Minimal re-renders for better performance ✅ Lightweight and scalable for complex forms ✅ Built-in validation support ✅ Easy integration with validation libraries like Yup Example: const { register, handleSubmit } = useForm(); <input {...register("projectName")} /> Using this approach significantly improved form performance, maintainability, and scalability in our application. Curious to hear from other developers 👇 What tools or libraries do you prefer for handling large forms in React applications? #reactjs #frontenddevelopment #javascript #typescript #webdevelopment #reacthookform
To view or add a comment, sign in
-
useRef is Not Just for DOM Access: Most React developers learn useRef for one thing: accessing a DOM element directly. And then they never think about it again. That is a mistake. useRef is one of the most underused and misunderstood hooks in React. Here is what it can actually do: -> Store previous values without triggering re-renders useState causes a re-render every time it changes. useRef does not. When you need to track a value across renders without causing the component to update, ref.current is the right tool. This is how you compare the current value of something to what it was on the previous render — without any side effects. -> Manage setTimeout and setInterval safely Timer IDs stored in state cause unnecessary re-renders. Timer IDs stored in refs do not. Keep your interval and timeout IDs in refs. Clear them reliably even when dependencies change. No race conditions. No stale closures catching you off guard. -> Persist values across renders Counters, focus state, scroll position — values that need to survive re-renders without driving them are perfect use cases for useRef. The final takeaway from this image is exactly right. Before reaching for useState, ask yourself one question: does this value need to trigger a re-render when it changes? If the answer is no, useRef is probably the better choice. Not every value that needs to be tracked needs to live in state. Knowing the difference is what separates developers who write performant React from developers who create unnecessary re-render chains without realizing it. What was the most useful non-DOM use case for useRef you have discovered? #React #useRef #FrontendDevelopment #JavaScript #WebDevelopment #ReactHooks
To view or add a comment, sign in
-
-
🚀 Project Update: React Card UI A simple card project built using React.js to show user details in a clean way. 🔗 GitHub Link: https://lnkd.in/gi56aNdJ ✨ Features: ✔ Show data using map() ✔ Clean and simple design ✔ Light and dark theme ⚙ Tech Stack: React.js | JavaScript | HTML | CSS This project helped improve basic React skills and understanding of UI. More projects coming soon. #ReactJS #FrontendDeveloper #WebDevelopment #JavaScript #Projects
To view or add a comment, sign in
-
🛑 Stop using nested ternaries in your React components. If you’ve built React apps with multiple user roles or complex statuses, you’ve probably seen the "JSX Pyramid of Doom." condition1 ? <A/> : condition2 ? <B/> : <C/> It works... until Product asks for a 4th and 5th variation. Suddenly, your return statement is a massive, unreadable block of ? and : . We already know that Guard Clauses fix messy business logic. But how do we fix messy JSX rendering? The easiest fix: The Component Map (Dictionary Pattern). 🗺️ Instead of writing if/else or chained ternaries inside your markup, map your conditions to their respective components using a simple JavaScript object. Why this wins: ✅ Readability: Your actual JSX return statement becomes exactly one line. ✅ Extensibility: Want to add a "Moderator" role? Just add one line to the object. You don't even have to touch the component logic. ✅ Performance: Object property lookup is O(1). No more evaluating chains of conditions. Stop forcing your JSX to do the heavy lifting. Let data structures do it for you. 🧠 Are you Team Ternary or Team Map? 👇 #ReactJS #FrontendDevelopment #CleanCode #JavaScript #TypeScript #WebDev #SoftwareArchitecture
To view or add a comment, sign in
-
-
⚛️ In React, these three onClick patterns look almost identical… but behave very differently. onClick={handleAddItem} onClick={handleAddItem(item)} onClick={() => handleAddItem(item)} At a glance they seem similar, but the execution timing is completely different. 🔹 onClick={handleAddItem} Passes the function reference → runs only when the click event occurs. 🔹 onClick={handleAddItem(item)} Executes immediately during render, not on click. This can lead to unexpected behavior like unnecessary API calls or extra re-renders. 🔹 onClick={() => handleAddItem(item)} Creates a callback function that runs on click and allows you to pass parameters. ✅ Rule of thumb • No parameters → onClick={handleAddItem} • Need parameters → onClick={() => handleAddItem(item)} • Avoid → onClick={handleAddItem(item)} 💡 One more interesting detail Arrow functions create a new function on every render. In most cases this is perfectly fine. However, in large lists or memoized components (React.memo), this can sometimes trigger unnecessary re-renders. That’s why some developers use useCallback or pre-defined handlers for optimization. 👨💻 How do you usually handle this in your projects? Arrow functions, useCallback, or another pattern? #React #JavaScript #FrontendDevelopment
To view or add a comment, sign in
-
🚀 Stop Using "Index" as a Key in Your Lists! Here’s Why. Ever wondered why React (or any modern UI framework) screams at you when you forget to add a key to a list? It’s not just a "coding rule"—it’s the secret sauce for performance and bug-free apps. Let’s break it down. 🧵 🔑 What is a "Key" anyway? Think of a list of items in your code like a coat check at a party. Without a tag (key), the attendant (React) has to look at every single coat to find yours. With a tag, they know exactly which one is yours instantly. A key is a unique identity. It helps the framework track which item was added, changed, or removed without re-rendering the entire list. 🚫 The "Index" Trap: Why key={index} is a bad idea We’ve all done it: items.map((item, index) => <li key={index}>...</li>). It stops the warning, but it creates a hidden bug. Here is the problem: Imagine you have a list of names: [0: "Alice", 1: "Bob", 2: "Charlie"]. If you delete "Alice," the list becomes: [0: "Bob", 1: "Charlie"]. Wait, what happened? "Bob" used to be index 1, but now he is index 0. React thinks index 0 just changed its text from "Alice" to "Bob." If you had a checkbox or a text input next to Alice, it might stay at index 0 and suddenly look like it belongs to Bob! Using an index is like identifying your friends by their "spot in line" rather than their "name." If someone leaves the line, everyone’s identity changes! ✅ The Golden Rule Always use a stable, unique ID from your data (like user.id or product.uuid). Better Performance: React only updates what actually changed. No UI Glitches: Your checkboxes, inputs, and animations stay attached to the right item. Happier Users: Smooth, fast, and bug-free interfaces. Keep your keys unique, keep your UI stable! 💻✨ #WebDevelopment #ReactJS #NextJS #Frontend #CodingTips #CleanCode #JavaScript
To view or add a comment, sign in
-
7 React Hooks You Must Master React Hooks replaced class components and changed how every React developer thinks about state, side effects, and performance. Master these 7 and you can handle 95 percent of React challenges. -> useState Your component's memory. Stores local state and triggers a re-render when it changes. The most used hook in React by a significant margin. -> useEffect Handles everything that happens outside the render cycle. API calls, subscriptions, timers, and DOM manipulation all live here. Runs after every render unless you control its dependency array. -> useContext Access global state without passing props through every level of the component tree. Works perfectly with the Context API for theme, auth, and shared configuration. -> useRef Two jobs: access DOM elements directly without a re-render, and store values that persist across renders without causing re-renders. More powerful than most developers realize when they first learn it. -> useMemo Memorizes the result of an expensive calculation. Only recalculates when its dependencies change. Use it when a computation is genuinely expensive and runs on every render. -> useCallback Memorizes a function reference between renders. When you pass a callback to a child component, useCallback prevents the child from re-rendering because it receives a new function reference every render. -> useReducer Complex state logic that involves multiple sub-values or state transitions that depend on the previous state. Think of it as a mini Redux built directly into React. More predictable than multiple useState calls for complex state. These seven hooks cover state management, side effects, performance optimization, and DOM interaction. Everything else in React builds on these foundations. Which of these seven do you use least and think you should probably use more? #React #ReactHooks #FrontendDevelopment #JavaScript #WebDevelopment #Developers
To view or add a comment, sign in
-
-
How I Understood React State Updates One day I wrote this small React code: import { useState } from "react"; export default function App() { const [count, setCount] = useState(0); const handleClick = () => { setCount(count + 1); setCount(count + 1); setCount(count + 1); console.log(count); }; console.log(count); return ( <div> <h1>{count}</h1> <button onClick={handleClick}>Increment</button> </div> ); } And I thought something very simple would happen. I clicked the button and expected: 0 → 3 Because I increased the count three times. But React surprised me. The value became: 0 → 1 And I asked myself: 👉 Why didn't it increase to 3? So I stopped thinking like a JavaScript developer… and started thinking like React. What React actually sees React batches state updates. All three lines read the same old value. setCount(count + 1); setCount(count + 1); setCount(count + 1); • For React, this becomes: setCount(1) setCount(1) setCount(1) • So the final result is simply: 1 Not 3. • The correct way When the new state depends on the previous state, React gives us a better pattern: setCount(prev => prev + 1); setCount(prev => prev + 1); setCount(prev => prev + 1); Now React updates step by step. Result: 0 → 3 The lesson I learned State updates in React are not immediate. React schedules them and processes them together. So whenever state depends on the previous value, I now ask myself: 👉 Should I use the functional update? Small detail. Big difference. Still learning React the human way. 🚀 #JavaScript #FrontendDevelopment #LearningInPublic #CleanCode #ReactJS #useState #FrontendDevelopment #LearningInPublic #JavaScript #WebDevelopment #DeveloperJourney #ReactHook
To view or add a comment, sign in
-
-
While working on React forms, I finally understood the real difference between useState and useRef — and it completely changed how I think about handling data. At first, both looked similar because both can store values. But their behavior is very different. 🔹 useState • Used to store data that affects UI • When state changes → component re-renders • Best for dynamic data (inputs, counters, UI updates) Example: form input, toggles, live data --- 🔹 useRef • Used to store values without re-rendering • Directly access DOM elements • Value persists across renders but doesn’t trigger UI update Example: accessing input field, focusing input, storing previous value --- 🧠 Simple way to understand: 👉 useState = “Update UI” 👉 useRef = “Store value without re-render” --- 💡 Real-world example: In a form: • useState → to store input value • useRef → to focus input or get value without re-render --- What I learned: Choosing the right hook improves performance and keeps code clean. Still learning React deeply and building projects step by step 🚀 #ReactJS #JavaScript #FrontendDevelopment #WebDevelopment #CodingJourney #LearnInPublic
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
Spot on. The 0 bug hits hard when you rely on cart.length &&. I switch to cart.length > 0 && <CheckoutButton /> or {cart.length ? <CheckoutButton /> : null}. Keeps UI predictable and avoids stray numbers.