ARTICLE AD BOX
Issue
You’re getting this error because on the initial render user is null, and this line: <h1>Street: {user.address.street}</h1> Tries to read address from null. React renders once before useEffect runs, so the data is not available yet.Fix
The fix is not just to guard the property access, but to conditionally render the UI based on whether the data exists.
The solution is an early return for the loading state:
import React, { useState, useEffect } from 'react'; function UserProfile() { const [user, setUser] = useState(null); useEffect(() => { setTimeout(() => { setUser({ name: 'Jane Doe', address: { street: '123 Main St', city: 'Anytown', }, }); }, 1000); }, []); if (!user) { return <div>Loading...</div>; } return ( <div> <h1>Street: {user.address.street}</h1> </div> ); } export default UserProfile;Root Cause of actual failure
user && user.address && user.address.street This prevents the crash, but during the initial render it evaluates to undefined, which React renders as nothing. That’s why you see a blank screen instead of a loading message. user?.address?.streetOptional chaining also prevents the error, but again it returns undefined when user is null.
React renders nothing for undefined, so you still get a blank screen.
Optional chaining solves the exception andIt does not provide a loading state.
Alternate fix
If you prefer inline conditional rendering instead of an early return: return ( <div> {user ? ( <h1>Street: {user.address.street}</h1> ) : ( <div>Loading...</div> )} </div> );Recommended Approach
For more complex cases, it’s often better to track loading explicitly: const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { setTimeout(() => { setUser({ name: 'Jane Doe', address: { street: '123 Main St', city: 'Anytown', }, }); setLoading(false); }, 1000); }, []); if (loading) { return <div>Loading...</div>; }The key point is that you should conditionally render based on data availability, not just defensively access nested properties.
