React
Beginner
1 min read
Early Returns and if/else in Components
Example
import { useState, useEffect } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
// Hooks MUST be called before any early return
useEffect(() => {
setLoading(true);
setError(null);
fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
.then(r => { if (!r.ok) throw new Error('Not found'); return r.json(); })
.then(data => { setUser(data); setLoading(false); })
.catch(err => { setError(err.message); setLoading(false); });
}, [userId]);
// Early returns — each guard is a separate if
if (loading) {
return <p style={{ color: '#888' }}>Loading user #{userId}…</p>;
}
if (error) {
return (
<div style={{ color: 'red', background: '#fee2e2', padding: 12, borderRadius: 6 }}>
<strong>Error:</strong> {error}
</div>
);
}
if (!user) {
return <p>No user found.</p>;
}
// Happy path — clean, no nesting
return (
<div style={{ border: '1px solid #ddd', padding: 16, borderRadius: 8 }}>
<h2>{user.name}</h2>
<p>Email: {user.email}</p>
<p>Phone: {user.phone}</p>
<p>Company: {user.company.name}</p>
</div>
);
}
export default UserProfile;