javascriptreactjsnode.jstypescriptjsx

What is the best way to render component by condition in React?


I have a component that needs to render by condition, I'm confused between the two ways like the code below and I am figuring out the recommended way of React. What is the best way to set render conditions for a component? I'm new to React and would love some help.

The first way:

const MyComponent1 = () => {
  return (
    <div>This is my component 1</div>
  )
}

{isRender && <MyComponent />}

The second way:

const MyComponent2 = ({ isRender }) => {
  if (!isRender) return null;

  return (
    <div>This is my component 2</div>
  )
}

<MyComponent isRender/>

I feel the second approach will redundancy the logic code inside this component if the component is not rendered (e.g: hooks, handle function, ...) The first way will not affect the CPU because the component is not rendered so the internal logic will not be executed. Is that true?


Solution

  • The first way is much better. As you rightly pointed out, you need to keep all hooks before the first return statement. You will be unnecessarily adding those hooks and any other logic when you don't need to render the component.

    Secondly, and more importantly, while using the first way you can use lazy loading to only load the component when it needs to be rendered for the first time and thereby improving the performance.