Early returns in React sub render function: return null, [], or React.Fragment?

9.5k Views Asked by At

Let's say I have a simple component that may or may not render a Counter.

What's the best practice in React to express a blocked code path? Should it return null, [], or a Fragment?

class App extends Component {
  renderCounter() {
    if (!this.props.shouldRenderCounter) {
      // // which should I return?
      // return; 
      // return null; 
      // return []; 
      // return <React.Fragment />; 
    }
    return <Counter />;
  }

  render() {
    return (
      <div>
        {this.renderCounter()}
      </div>
    );
  }
}

I think null is the clearest, but I can imagine it causing problems if the context around the return function expects a component. [] and Fragment both seem like fine options to me, except Fragment is a little easier to read. What's the difference?

2

There are 2 best solutions below

4
On BEST ANSWER

Returning null is recommended by the React team:

In rare cases you might want a component to hide itself even though it was rendered by another component. To do this return null instead of its render output.

3
On

You dont need to create an extra function for it.

This will do the job:

class App extends Component {
  render() {
    return (
      <div>
        {this.props.shouldRenderCounter && <Counter />}
      </div>
    );
  }
}