Category: react
handle undefined variables in React
Published on 22 Apr 2026
Explanation
Use optional chaining (?.) to safely access
nested object properties without
.crashing when a
variable is undefined.
Code:
const username = user?.name;
Explanation
Provide a default fallback value using
logical
OR (||) if the variable is undefined
or null.
Code:
const username = user.name || 'Guest User';
Explanation
Use nullish coalescing (??) to assign a
default value only when the variable is
null or undefined.
Code:
const username = user.name ?? 'Guest User';
Explanation
Conditionally render JSX using && to avoid
accessing undefined values.
Code:
{user && <p>{user.name}</p>}
Explanation
Use a ternary operator to check if
a variable exists before rendering.
Code:
{user ? <p>{user.name}</p> :
<p>Loading...</p>}
Explanation
Initialize state properly using useState
to prevent
undefined errors during initial render.
Code:
const [user, setUser] = useState(
{ name: '' }
);
Explanation
Use default props in functional
components to
handle missing values.
Code:
function Profile({ name = 'Guest User' })
{ return <h1>{name}</h1>;
}