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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With