Early return
- React course
- Beginner
- Lesson 25/84
- 4 min
Learn to return null or fallback content early from a component.
Early return
The early return pattern checks a condition at the top of the component and exits early if it doesn't hold. Like if (!user) return null;.
This pattern improves readability for complex conditions. Instead of nesting ternaries, you handle conditions one by one and early-return for each.
Early return usually returns null, but it can also return a fallback JSX: if (!user) return <Login />;.
Early return advantage
The biggest advantage of early return is highlighting the happy path. The main logic stays at the bottom; the early returns at the top handle edge cases.
This keeps the code flat: each condition sits on its own line, no nested blocks. It's easy to maintain.
But early returns for every condition can get messy. With more than two or three conditions, consider a helper function.
Practice LoadingGuard early return
Complete the skeleton. Write a component called LoadingGuard that takes ({ '{ loading }' }) as parameter. If loading === true, early return <p>Loading</p>; otherwise return <p>Ready</p>. Don't forget to export.
Starter code
// Write the LoadingGuard component hereSample solution
function LoadingGuard({ loading }) {
if (loading === true) return <p>Loading</p>;
return <p>Ready</p>;
}
export default LoadingGuard;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does early return return?
- effect
- state
- DOM
- null or fallback JSX Correct answer
Explanation: Early return usually returns null or fallback JSX.
2 Early return example
Early return usually returns ____.
Early return usually returns null.
Explanation: null is a value React doesn't render.
3 Match the early return pattern
| Term | Meaning |
|---|---|
if (!user) |
Condition |
return null |
Early exit |
return <Login /> |
Fallback |
if (loading) |
Another condition |