[{"data":1,"prerenderedAt":115},["ShallowReactive",2],{"qa-\u002Freact\u002Fcomponents\u002Fconditional-rendering":3},{"page":4,"siblings":95,"blog":112},{"id":5,"title":6,"body":7,"description":11,"difficulty":14,"extension":15,"framework":16,"frameworkSlug":17,"meta":18,"navigation":20,"order":21,"path":22,"questions":23,"questionsCount":86,"related":87,"seo":88,"seoDescription":89,"stem":90,"subtopic":6,"topic":91,"topicSlug":92,"updated":93,"__hash__":94},"qa\u002Freact\u002Fcomponents\u002Fconditional-rendering.md","Conditional Rendering",{"type":8,"value":9,"toc":10},"minimark",[],{"title":11,"searchDepth":12,"depth":12,"links":13},"",2,[],"easy","md","React","react",{"subtopicSlug":19},"conditional-rendering",true,4,"\u002Freact\u002Fcomponents\u002Fconditional-rendering",[24,28,32,37,41,45,49,53,57,61,65,69,73,77,81],{"id":25,"difficulty":14,"q":26,"a":27},"ways-to-conditionally-render","What are the main ways to conditionally render content in React?","React has four idiomatic patterns:\n\n```jsx\n\u002F\u002F 1. Logical && — render right side only when left is truthy\n{isLoggedIn && \u003CDashboard \u002F>}\n\n\u002F\u002F 2. Ternary — render one of two options\n{isLoggedIn ? \u003CDashboard \u002F> : \u003CLogin \u002F>}\n\n\u002F\u002F 3. Variable \u002F if-else above return\nlet content = isLoggedIn ? \u003CDashboard \u002F> : \u003CLogin \u002F>\nreturn \u003Cmain>{content}\u003C\u002Fmain>\n\n\u002F\u002F 4. Early return — bail out of the component entirely\nif (!isLoggedIn) return \u003CLogin \u002F>\nreturn \u003CDashboard \u002F>\n```\n\nEach has its place:\n- `&&` — one branch only, very readable when the condition is simple.\n- Ternary — exactly two branches.\n- Variable \u002F if-else — complex conditions with more than two outcomes.\n- Early return — guard clause at the top when the component shouldn't\n  render at all in certain states.\n\n**Rule of thumb:** use the simplest form that's still readable. If a\nternary has nested ternaries, it's time for an if-else or a variable.\n",{"id":29,"difficulty":14,"q":30,"a":31},"and-operator","How does the && operator work for conditional rendering?","JavaScript's `&&` returns the **last evaluated operand** — not necessarily\na boolean. React renders whatever value appears on the right side of `&&`\nwhen the left side is truthy.\n\n```jsx\nconst count = 5\nreturn (\n  \u003Cdiv>\n    {count > 0 && \u003CBadge count={count} \u002F>}\n    {\u002F* → renders \u003CBadge \u002F> because (count > 0) is true *\u002F}\n  \u003C\u002Fdiv>\n)\n```\n\nWhen the condition is `false`, `&&` short-circuits and returns `false`.\nReact treats `false` as \"render nothing\" — no output.\n\n**Rule of thumb:** `{condition && \u003CElement \u002F>}` is idiomatic React. The\ncondition should be a boolean; if in doubt, cast it: `{!!value && \u003CX \u002F>}`.\n",{"id":33,"difficulty":34,"q":35,"a":36},"falsy-zero-bug","medium","What is the \"falsy zero\" bug with the && operator?","`&&` returns the **left operand** when it is falsy. If that operand is `0`,\nReact renders the number `0` (since `0` is a valid renderable value).\n\n```jsx\nconst messages = []    \u002F\u002F length is 0\n\n\u002F\u002F ❌ Renders \"0\" when messages is empty\nreturn \u003Cdiv>{messages.length && \u003CMessageList items={messages} \u002F>}\u003C\u002Fdiv>\n\n\u002F\u002F ✅ Force the left side to a boolean\nreturn \u003Cdiv>{messages.length > 0 && \u003CMessageList items={messages} \u002F>}\u003C\u002Fdiv>\n\n\u002F\u002F ✅ Or use Boolean()\nreturn \u003Cdiv>{Boolean(messages.length) && \u003CMessageList items={messages} \u002F>}\u003C\u002Fdiv>\n\n\u002F\u002F ✅ Or use a ternary\nreturn \u003Cdiv>{messages.length ? \u003CMessageList items={messages} \u002F> : null}\u003C\u002Fdiv>\n```\n\n**Rule of thumb:** never use `count &&` or `array.length &&` directly.\nAlways compare: `count > 0 &&` or `array.length > 0 &&`. The same trap\nexists for any number that could be `0`.\n",{"id":38,"difficulty":14,"q":39,"a":40},"ternary-rendering","How do you use a ternary for conditional rendering?","The ternary expression (`condition ? a : b`) is a JavaScript expression and\nis legal inside JSX `{}`. It's the idiomatic way to render one of two\nalternatives.\n\n```jsx\nfunction AuthStatus({ isLoggedIn, username }) {\n  return (\n    \u003Cheader>\n      {isLoggedIn\n        ? \u003Cspan>Welcome, {username}!\u003C\u002Fspan>\n        : \u003Ca href=\"\u002Flogin\">Sign in\u003C\u002Fa>\n      }\n    \u003C\u002Fheader>\n  )\n}\n```\n\nUse `null` for the false branch when you want to render nothing:\n\n```jsx\n{isAdmin ? \u003CAdminPanel \u002F> : null}\n\u002F\u002F Equivalent to:\n{isAdmin && \u003CAdminPanel \u002F>}\n```\n\n**Rule of thumb:** ternaries are great for exactly two outcomes. For more\nthan two, a variable or a helper function is cleaner.\n",{"id":42,"difficulty":34,"q":43,"a":44},"when-to-use-which","When should you use if\u002Felse, ternary, or && for conditional rendering?","Choose based on the number of outcomes and complexity:\n\n| Pattern | Best for |\n|---------|----------|\n| `&&` | Single optional element; condition is a simple boolean |\n| Ternary | Exactly two alternatives; fits on one or two lines |\n| `if\u002Felse` above return | Multiple alternatives; complex conditions; shared logic before branching |\n| Early `return` | Guard clause — component has nothing to show in this state |\n\n```jsx\n\u002F\u002F && — simple optional\n{hasError && \u003CErrorBanner message={error} \u002F>}\n\n\u002F\u002F Ternary — two outcomes\n{loading ? \u003CSpinner \u002F> : \u003CContent data={data} \u002F>}\n\n\u002F\u002F if\u002Felse — three outcomes\nlet body\nif (loading) body = \u003CSpinner \u002F>\nelse if (error) body = \u003CError message={error} \u002F>\nelse body = \u003CContent data={data} \u002F>\nreturn \u003Cmain>{body}\u003C\u002Fmain>\n\n\u002F\u002F Early return — guard clause\nif (!user) return null\nreturn \u003CProfile user={user} \u002F>\n```\n\n**Rule of thumb:** default to simplicity. Reach for `&&` first, ternary\nfor two branches, if\u002Felse for three or more. Never nest ternaries more\nthan one level deep.\n",{"id":46,"difficulty":14,"q":47,"a":48},"returning-null","How do you render nothing from a component?","Return `null`. React renders nothing to the DOM but the component remains\nmounted — its `useEffect` hooks still run and refs still attach.\n\n```jsx\nfunction Tooltip({ visible, text }) {\n  if (!visible) return null\n  return \u003Cdiv className=\"tooltip\">{text}\u003C\u002Fdiv>\n}\n```\n\nOther falsy values behave differently:\n- `undefined` — React 18+ allows returning `undefined` from a component\n  (was an error in older versions). Treated like `null`.\n- `false` — valid child; renders nothing.\n- `0` — renders the digit `0`. Careful!\n- Empty string `''` — renders nothing visible but creates a text node.\n\n**Rule of thumb:** return `null` (not `false` or `undefined`) when you\nwant a component to render nothing — it's explicit and unambiguous.\n",{"id":50,"difficulty":34,"q":51,"a":52},"display-none-vs-conditional","What is the difference between CSS display:none and conditional rendering?","- **CSS `display:none`** — the element is in the DOM, painted, and React's\n  tree, but invisible. State, refs, effects, and event listeners are all live.\n- **Conditional rendering** — the element is not in the DOM. When the\n  condition becomes false, React unmounts the component: state is reset,\n  effects clean up, and refs detach.\n\n```jsx\n\u002F\u002F CSS approach — DOM node always present, just hidden\n\u003Cdiv style={{ display: isVisible ? 'block' : 'none' }}>\n  \u003CExpensiveWidget \u002F>   {\u002F* still mounted, effects running *\u002F}\n\u003C\u002Fdiv>\n\n\u002F\u002F Conditional — component unmounts when isVisible is false\n{isVisible && \u003CExpensiveWidget \u002F>}\n```\n\nUse cases:\n- Prefer conditional rendering when you want fresh state on each appearance.\n- Prefer `display:none` when mounting\u002Funmounting is expensive (e.g. a heavy\n  widget) or when you must preserve internal state across hides.\n\n**Rule of thumb:** default to conditional rendering. Use CSS visibility only\nwhen remounting is measurably expensive or state preservation is required.\n",{"id":54,"difficulty":14,"q":55,"a":56},"conditional-class","How do you conditionally apply a CSS class in JSX?","Use a ternary or template literal inside `className`:\n\n```jsx\n\u002F\u002F Ternary — toggle between two class names\n\u003Cbutton className={isActive ? 'btn btn-active' : 'btn'}>Click\u003C\u002Fbutton>\n\n\u002F\u002F Template literal — build up from base + optional modifier\n\u003Cdiv className={`card ${isHighlighted ? 'card-highlighted' : ''}`}>…\u003C\u002Fdiv>\n\n\u002F\u002F For multiple conditional classes, clsx\u002Fclassnames library is cleaner\nimport clsx from 'clsx'\n\u003Cdiv className={clsx('card', { 'card-highlighted': isHighlighted, 'card-error': hasError })}>\n  …\n\u003C\u002Fdiv>\n```\n\nAvoid complex string concatenation inline — it becomes unreadable quickly.\n\n**Rule of thumb:** for more than one or two conditional classes, add `clsx`\n(or `classnames`) to the project — it handles undefined\u002Ffalse values\ncleanly and the API is easy to scan.\n",{"id":58,"difficulty":34,"q":59,"a":60},"role-based-rendering","How do you render different content based on user role or permission?","Extract the guard logic into a dedicated component or hook to keep the\nrendering logic clean.\n\n```jsx\n\u002F\u002F Simple inline\n{user.role === 'admin' && \u003CAdminPanel \u002F>}\n\n\u002F\u002F Reusable gate component\nfunction Can({ role, children }) {\n  const { user } = useAuth()\n  return user.role === role ? children : null\n}\n\n\u002F\u002F Usage\n\u003CCan role=\"admin\">\n  \u003CDeleteButton \u002F>\n\u003C\u002FCan>\n\n\u002F\u002F Or a hook\nfunction usePermission(requiredRole) {\n  const { user } = useAuth()\n  return user.role === requiredRole\n}\n\nconst canDelete = usePermission('admin')\n{canDelete && \u003CDeleteButton \u002F>}\n```\n\n**Rule of thumb:** keep auth\u002Fpermission logic out of individual components.\nA `\u003CCan>` component or `usePermission` hook keeps it testable and reusable\nacross the app.\n",{"id":62,"difficulty":34,"q":63,"a":64},"switch-rendering","Can you use a switch statement for conditional rendering?","Yes, but a switch statement can't go directly inside JSX. Extract it into\na helper function or variable.\n\n```jsx\nfunction StatusBadge({ status }) {\n  function renderBadge() {\n    switch (status) {\n      case 'success': return \u003Cspan className=\"badge green\">Success\u003C\u002Fspan>\n      case 'error':   return \u003Cspan className=\"badge red\">Error\u003C\u002Fspan>\n      case 'loading': return \u003CSpinner \u002F>\n      default:        return null\n    }\n  }\n\n  return \u003Cdiv className=\"status\">{renderBadge()}\u003C\u002Fdiv>\n}\n```\n\nAn object map is often cleaner than switch for this pattern:\n\n```jsx\nconst BADGE = {\n  success: \u003Cspan className=\"badge green\">Success\u003C\u002Fspan>,\n  error:   \u003Cspan className=\"badge red\">Error\u003C\u002Fspan>,\n  loading: \u003CSpinner \u002F>,\n}\n\nreturn \u003Cdiv>{BADGE[status] ?? null}\u003C\u002Fdiv>\n```\n\n**Rule of thumb:** object maps are more idiomatic React than switch\nstatements for rendering; switch is fine when you need fallthrough or `break`\nbehavior.\n",{"id":66,"difficulty":34,"q":67,"a":68},"avoid-nested-ternaries","How do you avoid deeply nested ternaries in JSX?","Extract the logic to a variable, early return, or helper function before\nthe `return`.\n\n```jsx\n\u002F\u002F ❌ Nested ternary — hard to read\nreturn (\n  \u003Cdiv>\n    {loading\n      ? \u003CSpinner \u002F>\n      : error\n        ? \u003CError message={error} \u002F>\n        : data\n          ? \u003CDataView data={data} \u002F>\n          : \u003CEmpty \u002F>}\n  \u003C\u002Fdiv>\n)\n\n\u002F\u002F ✅ Variable approach\nlet content\nif (loading)     content = \u003CSpinner \u002F>\nelse if (error)  content = \u003CError message={error} \u002F>\nelse if (data)   content = \u003CDataView data={data} \u002F>\nelse             content = \u003CEmpty \u002F>\n\nreturn \u003Cdiv>{content}\u003C\u002Fdiv>\n\n\u002F\u002F ✅ Helper component\nfunction AsyncContent({ loading, error, data }) {\n  if (loading) return \u003CSpinner \u002F>\n  if (error)   return \u003CError message={error} \u002F>\n  if (!data)   return \u003CEmpty \u002F>\n  return \u003CDataView data={data} \u002F>\n}\n```\n\n**Rule of thumb:** if a ternary needs to be nested, refactor to if\u002Felse\nor extract a component. A long chain of nested ternaries is a refactoring\nsignal, not a clever trick.\n",{"id":70,"difficulty":34,"q":71,"a":72},"loading-error-states","What is the pattern for handling loading and error states in rendering?","The guard-clause \u002F early-return pattern keeps the happy path last:\n\n```jsx\nfunction UserProfile({ userId }) {\n  const { data: user, loading, error } = useUser(userId)\n\n  if (loading) return \u003CSkeleton \u002F>\n  if (error)   return \u003CErrorMessage error={error} \u002F>\n  if (!user)   return null\n\n  \u002F\u002F Happy path — no nesting, no clutter\n  return (\n    \u003Carticle>\n      \u003Ch1>{user.name}\u003C\u002Fh1>\n      \u003Cp>{user.bio}\u003C\u002Fp>\n    \u003C\u002Farticle>\n  )\n}\n```\n\nThis pattern is sometimes called \"bail early, render late.\" Each guard\nhandles one sad path and returns, leaving the main render clean.\n\n**Rule of thumb:** load state first, error state second, empty\u002Fnull state\nthird, happy path last. This order prevents accidentally rendering\nundefined properties.\n",{"id":74,"difficulty":14,"q":75,"a":76},"short-circuit-evaluation","What is short-circuit evaluation and how does it apply to conditional rendering?","Short-circuit evaluation means JavaScript stops evaluating an expression as\nsoon as the result is determined:\n- In `A && B` — if `A` is falsy, `B` is never evaluated.\n- In `A || B` — if `A` is truthy, `B` is never evaluated.\n\nReact leverages `&&` for conditional rendering because when the condition\nis false, the right-hand component is not evaluated (and thus not rendered):\n\n```jsx\n\u002F\u002F UserMenu is never evaluated when isLoggedIn is false\n{isLoggedIn && \u003CUserMenu user={user} \u002F>}\n\n\u002F\u002F Useful for expensive renders or components that crash on missing data\n{user && user.isAdmin && \u003CAdminPanel \u002F>}\n```\n\n**Rule of thumb:** short-circuit with `&&` when you have one optional\nelement and no fallback. Use `||` for default values, not for conditional\nrendering — `{value || \u003CFallback \u002F>}` renders `\u003CFallback \u002F>` whenever\n`value` is falsy (including `0` and `''`).\n",{"id":78,"difficulty":34,"q":79,"a":80},"nullish-coalescing","What is the nullish coalescing operator and when is it useful in JSX?","`??` returns the right operand only when the left is `null` or `undefined`\n(not for `0`, `''`, or `false`). This makes it safer than `||` for default\nvalues.\n\n```jsx\n\u002F\u002F || treats 0 and '' as falsy — may swallow valid values\n\u003Cp>Score: {score || 'No score'}\u003C\u002Fp>\n\u002F\u002F If score is 0, renders \"No score\" — wrong!\n\n\u002F\u002F ?? treats only null\u002Fundefined as \"missing\"\n\u003Cp>Score: {score ?? 'No score'}\u003C\u002Fp>\n\u002F\u002F If score is 0, renders \"0\" — correct\n\n\u002F\u002F Common in JSX for optional labels, counts, or display values\n\u003Ch2>{user.displayName ?? user.email}\u003C\u002Fh2>\n```\n\n**Rule of thumb:** use `??` for \"provide a fallback when the value is\nmissing.\" Use `||` only when you intentionally want `0`, `false`, and `''`\nto also trigger the fallback.\n",{"id":82,"difficulty":83,"q":84,"a":85},"suspense-lazy-conditional","hard","How do React.lazy and Suspense relate to conditional rendering?","`React.lazy` lets you load a component's code on demand. `Suspense`\nprovides a fallback to show while the lazy component loads — effectively\na built-in conditional-rendering pattern for async code splitting.\n\n```jsx\nimport { lazy, Suspense } from 'react'\n\nconst AdminPanel = lazy(() => import('.\u002FAdminPanel'))\n\nfunction App({ user }) {\n  return (\n    \u003CSuspense fallback={\u003CSpinner \u002F>}>\n      {user.isAdmin && \u003CAdminPanel \u002F>}\n    \u003C\u002FSuspense>\n  )\n}\n```\n\nWhen `\u003CAdminPanel \u002F>` is first rendered, React suspends, the nearest\n`\u003CSuspense>` shows `\u003CSpinner \u002F>`, and the bundle chunk loads in the\nbackground. On completion React retries the render and shows the panel.\n\n**Rule of thumb:** combine `lazy` + `Suspense` with normal conditional\nrendering. `Suspense` handles the *loading* state of the import; your\n`&&` or ternary handles the *permission* or *visibility* condition.\n",15,null,{"description":11},"React conditional rendering interview questions — ternary, &&, null, guard clauses, loading states, CSS display vs conditional mounting, and clean multi-condition patterns.","react\u002Fcomponents\u002Fconditional-rendering","Components","components","2026-06-23","rh-A8_S8gjIU82IuQOu1zQklJ_cBcEkCZg5aTFr7yCQ",[96,100,103,107,108],{"subtopic":97,"path":98,"order":99},"JSX and Rendering","\u002Freact\u002Fcomponents\u002Fjsx-rendering",1,{"subtopic":101,"path":102,"order":12},"Props and Component Types","\u002Freact\u002Fcomponents\u002Fprops-component-types",{"subtopic":104,"path":105,"order":106},"Event Handling","\u002Freact\u002Fcomponents\u002Fevent-handling",3,{"subtopic":6,"path":22,"order":21},{"subtopic":109,"path":110,"order":111},"Lists and Keys","\u002Freact\u002Fcomponents\u002Flists-keys",5,{"path":113,"title":114},"\u002Fblog\u002Freact-conditional-rendering-guide","React Conditional Rendering — A Complete Interview Guide",1782244100883]