liveBook · Manning

Early return

As explained in React Quickly, Second Edition

An early return exits a function before its later statements execute when a condition makes further processing unnecessary.

An early return exits a React component before later statements run when rendering is unnecessary. Returning null renders nothing and avoids extra calculations or JSX creation. section 3.2.6

Countdown that stops at zero

Check the stopping condition first: if remaining time is zero, return null. Otherwise, calculate minutes and seconds, then return the countdown paragraph. section 3.2.6

class Countdown extends Component {
 render() {
   if (this.props.remaining === 0) {
     return null;
   }
   const seconds = this.props.remaining % 60;
   const minutes = Math.floor(this.props.remaining / 60);
   return <p>{minutes}:{seconds}</p>;
 }
}

Compare the early-return version with the longer conditional version to see how the failed condition implicitly skips the remaining render code. section 3.2.6

How React Quickly, Second Edition covers it

How deep it goes
Explains the null-return pattern and its short-circuiting rationale, but stops short of broader component-branching alternatives.
Examples
Uses a Countdown component that returns null at zero before calculating minutes, seconds, and JSX.
What it assumes
Assumes basic JavaScript conditionals, function returns, JSX, and React component rendering.
What you can do after
Apply early return to simplify components that render nothing under a stopping condition.
How it connects
Connects early return with JSX, conditional rendering, React components, ternary operators, and logical AND operators.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Quickly, Second Edition. The section links point to the parts of the book it draws on.