Conditional Rendering in React.js
Depending on certain situations or the state of your application, you can display alternative elements or components using React.js sophisticated conditional rendering mechanism. Building responsive and dynamic user interfaces that adjust to changing application logic, user interactions, or data changes requires this fundamental ability.

Let’s imagine we want the following behaviour. When we click on a heading (let’s say a h3 element), we want an input box to appear so we can change the heading name. React uses if else statements and component states to make this very easy to understand.
Why Conditional Rendering is Essential
The goal of React.js applications is to make them responsive and engaging. Frequently, this implies that specific UI elements should only be accessible or functional in specific situations. You may need to, for example:
- Invalid input fields are the only ones that cause an error message to appear. Class name conflicts are not a recent issue in CSS, and several attempts have been made to address them with naming conventions like BEM.
- Display a “shimmer UI” or loading spinner when getting API data. Your new component is loading in the browser. Suspense will allow you to load data in nested components without render blocking in next React versions.
- Give authenticated users a “Logout” button and others a “Login” button. Short circuting will be used to accomplish this. This implies that you will employ a conditional rendering, which will return the data in the second section if the first portion is true.
- Form fields can be disabled under certain conditions. Like other React components, components re-render when data changes when values and attributes are set dynamically.
- Routing libraries let you manage navigation and display URL-based content. Routers in React aid in the creation and navigation of the various URLs that comprise your online application.
Your user interface will be seamless and intuitive if you use conditional rendering to make sure it appropriately reflects the application’s state.
How Conditional Rendering Works in React
React uses JavaScript’s conditional logic in JSX. JavaScript code can be written using HTML-like syntax using JSX, a markup language React parses before putting it into the DOM. This integration lets you effortlessly combine JavaScript expressions, functions, and conditional operators into UI markup. React refreshes only the necessary DOM elements when a condition changes. React gives developers a virtual DOM to render to instead of the actual DOM. It finds the difference between the real and virtual DOMs and performs the fewest DOM operations needed to change state.
Also declarative, React. When data changes, React conceptually hits refresh and updates only the altered sections. “Re-rendering can be costly, Shawn. React.js is clever about it, though. Only the modified portion is rendered. The entire page does not have to be rendered again. It is also wise to minimise the amount of DOM modification.
Common Methods for Conditional Rendering
There are several techniques to perform conditional rendering in React:
Using if/else Statements (Outside JSX) with Element Variables: Although JSX cannot employ if/else statements directly, they can be used outside the return block to define which components or elements are rendered. A variable that has been assigned the outcome of the if/else logic can then be included in your JSX.
This approach is especially helpful when rendering completely separate sets of components depending on a condition or when the conditional logic is complicated.
Conditional (Ternary) Operator (?:): The ternary operator makes adding if/else logic to JSX simple. A condition, expression to report if true, and expression to report if false are needed.
This is perfect for basic toggles or situations when you have to select between two rendering options in a single line. Take <h1>{i == 1 as an example. “True!”: “False”Should i be 1, </h1> will show ‘True!’; if not, ‘False’.
Logical AND (&&) Operator (Short-Circuiting): The logical AND operator (&&) is a popular and idiomatic method for conditionally rendering an element or component only when a condition is true. Short-circuiting. JavaScript && expressions with truthy first operands evaluate to second operands. The expression returns the first operand or false if false.
React renders the second portion of the && expression if the condition is true. False conditions prevent React from rendering. The element will not be in the final HTML markup; this is not just CSS concealment.
Caveat with Falsy Values: Common JavaScript errors include using “falsy” variables like 0 with &&. When the array is empty and MessageList messages=props.messages /> is present, the length field will be 0. User interfaces with “0” are frequently terrible. Props.messages.length > 0 && <MessageList messages={props.messages} /> should always evaluate to a strict boolean.
Returning null or undefined from a Component’s render Method: Null or undefined render methods or functional component returns do not render in React. This helpful method conditionally hides DOM components without rendering a blank div or other placeholder.
Dynamically Setting Attributes and Props: React enables you to set properties and attributes on components in real time in response to changing data. The component will re-render and display the updated attribute state as a result of this. An input field that has been conditionally disabled is a typical example.
Code Example:
import React, { useState, useReducer } from 'react';
function OptionalMessage({ show }) {
return show ? <p>This message is conditionally shown.</p> : null;
}
function AuthStatus({ isLoggedIn, userType }) {
return (
<div>
<h2>{isLoggedIn ? `Welcome, {userType}!` : 'Please log in.'}</h2>
{isLoggedIn && <button>Log Out</button>}
<p>{userType === 'admin' ? 'Admin privileges' : 'Standard user'}
</div>
);
}
function reducer(state, action) {
return action.type === 'TOGGLE' ? !state : state;
}
export default function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [userType, setUserType] = useState('user');
const [showText, dispatch] = useReducer(reducer, false);
return (
<div style={{ padding: 20 }}>
<h1>Conditional Rendering</h1>
<button onClick={() => setIsLoggedIn(!isLoggedIn)}>
{isLoggedIn ? 'Log Out' : 'Log In'}
</button>
<button onClick={() => setUserType(userType === 'admin' ? 'user' : 'admin')}>
Switch to {userType === 'admin' ? 'User' : 'Admin'}
</button>
<AuthStatus isLoggedIn={isLoggedIn} userType={userType} />
<label>
<input type="checkbox" disabled={userType !== 'admin'} />
Admin-only checkbox
</label>
<button onClick={() => dispatch({ type: 'TOGGLE' })}>
Toggle Text
</button>
{showText && <p>Toggle-controlled paragraph.</p>}
<OptionalMessage show={isLoggedIn} />
</div>
);
}
Output:
Conditional Rendering
Log OutSwitch to Admin
Welcome, user!
Log Out
Standard user
Admin-only checkbox Toggle Text
This message is conditionally shown.
Explanation of the Code Example
OptionalMessage Component: Returning null is demonstrated by the optional message component. The component’s render (or return) method explicitly returns null if the show prop is set to false, which prevents that component from having any rendering in the DOM.
AuthStatus Component: A separate header message (Welcome, {userType}!, or Please log in.) is rendered dependent on the isLoggedIn prop using a ternary operator (?:). The logical AND (&&) operator is also used to show a “Log Out” button only in the event that isLoggedIn is true.
The && expression evaluates to false if isLoggedIn is false, and React.js does not render anything. Content relevant to the admin is displayed using a different ternary.
App Component: UseState Hook to manage the isLoggedIn and userType states. To show or conceal a paragraph using the && operator, useReducer controls the displayAction state. A checkbox input’s disabled property is dynamically set in this example. ‘admin’ is the only userType that makes the checkbox active (disabled={false}).
Advanced Conditional Rendering & Performance Considerations
Simple conditional rendering can be easily implemented, but further methods are needed to maximise speed in bigger systems, particularly when handling intricate computations or components that need to be rendered frequently:
ShouldComponentUpdate (for Class Components): You can decide if a component should re-render using this lifecycle function. In order to re-render when new props or state are received, React, if implemented, calls shouldComponentUpdate first. In order to save time and improve efficiency, React skips the re-render for that component and its children if it returns false. To prevent minor issues where a component might not update when it should, it often returns true.
React.memo (for Functional Components): Like shouldComponentUpdate, React.memo optimises functional components. Due to memoization, React will only re-render a component with minimal prop changes. This works well when a parent component frequently re-renders but its props don’t change.
useMemo Hook: Cache expensive computations with useMemo Hook. If its dependents (dependency array values) change, the function will only be performed again. Although the component may re-render for other reasons, this prevents repeated calculations.
useCallback Hook: React.memo and useMemo are often used with useCallback Hook to memoize functions. When a function is supplied as a prop to a child component (especially a memoized one), UseCallback keeps the function reference the same across renderings to avoid wasteful re-rendering. Even a semantically identical function prop is referentially different on each parent render.
React.lazy and Suspense (for Lazy Loading): Divide larger applications’ code into smaller chunks to speed up initial load times with React.lazy and Suspense. Dynamic import with React.lazy loads the code bundle only when the component is displayed. React.Suspense works.lazy to display a spinner, loading message, or “shimmer UI” while the component’s code loads. This method is also useful for waiting for API data after page load.
These sophisticated tools assist you in optimising the rendering behaviour of your React.js apps, guaranteeing peak performance even as they grow in size and complexity.
Conclusion
To sum up, conditional rendering is a fundamental React idea that enables programmers to create dynamic, effective, and user-responsive applications. React makes it possible for components to be displayed dynamically depending on the state of the application or props by utilising JavaScript conditional rendering logic in JSX. Each approach provides flexibility to satisfy different UI requirements, whether it is by returning null, using logical AND (&&), if/else expressions, the ternary operator, or dynamically setting props and attributes.
Additionally, sophisticated methods like React.memo, useMemo, useCallback, and React.lazy in conjunction with Suspense guarantee that components render appropriately as applications grow, minimising needless re-renders and enhancing efficiency. with the end, becoming proficient with conditional rendering helps create reliable and maintainable React apps in addition to improving user experience.