Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

How to stop a React component from rendering

In React, when you want don’t want a component to render based on some condition, you might reach for short-circuiting to achieve the same.

Check the following example.

import Header from "./Header";

export default function App() {
  const shouldRender = true;

  return (
    <>
      {shouldRender && <Header />}
      <div className="App">
        <h1>App Body</h1>
        <h2>This is app body</h2>
      </div>
    </>
  );
}

As you can tell, the Header component will render if the shouldRender variable is true and will not render if the shouldRender variable is false. This works fine but recently I learned that there is one more way to achieve the same.

Returning null from the component

In React, you can return null from a component to indicate that it should render nothing. So, we can tweak the above example to return null from the Header component if the shouldRender variable is false like so.

To do so, we can pass shouldRender as a prop to the Header component like so.

import Header from "./Header";

export default function App() {
  const shouldRender = true;

  return (
    <>
      <Header shouldRender={shouldRender} />
      <div className="App">
        <h1>App Body</h1>
        <h2>This is app body</h2>
      </div>
    </>
  );
}

And then, we can tweak the Header component to return null if the shouldRender prop is false like so.

export default function Header({ shouldRender }) {
  if (!shouldRender) {
    return null;
  }

  return (
    <div className="App">
      <h1>App Header</h1>
    </div>
  );
}

A lot cleaner than the short-circuiting, isn’t it?

I have put together a CodeSandbox to demonstrate the same.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?