skip to Main Content

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?

3

Answers


  1. 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.

    Login or Signup to reply.
  2. Both ways you provided are valid approaches in React, and the choice between them can depend on the context and complexity of your code.

    1. The first way:

    This is called a conditional rendering with a short-circuit evaluation. The component will be rendered only if the condition (isRender in this case) is true. It is a concise way of conditionally showing the component, and it’s generally recommended for simple cases like this.

    1. The second way:

    This is another form of conditional rendering using a function component and an explicit if statement. It allows you to control the rendering based on the isRender prop. This method might be more suitable when the component’s rendering logic becomes more complex and requires multiple conditions or calculations before rendering.

    Both approaches are widely used in React, and the choice depends on your specific use case and preferences. If your rendering logic is straightforward and doesn’t require additional conditions, the first way is simpler and more concise. If the rendering logic is more complex and involves multiple conditions, the second way with an explicit if statement might be a better fit.

    Also You can also use the ternary operator for concise conditional rendering:

    const MyComponent3 = ({ isRender }) => (
      isRender ? <div>This is my component 3</div> : null
    );
    

    or If you have multiple conditions to handle, you can use a switch statement:

    const MyComponent4 = ({ status }) => {
      switch (status) {
        case 'render1':
          return <div>This is my component 4 - Render 1</div>;
        case 'render2':
          return <div>This is my component 4 - Render 2</div>;
        default:
          return null;
      }
    };
    
    Login or Signup to reply.
  3. among the most common strategies are:

    Employing the if/else or ternary operator:

    To conditionally render components, you can use either a standard if/else expression or a ternary operator. Here is an illustration of the ternary operator in use:

    function MyComponent({ isLoggedIn }) {
    
     return (
        <div>
          {isLoggedIn ? <LoggedInComponent /> : <LoggedOutComponent />}
        </div>
      );
    }
    

    Using && operator:
    The && operator can be used for simple conditional rendering when you want to render a component based on a single condition:

    function MyComponent({ isLoading }) {
      return (
        <div>
          {isLoading && <LoadingComponent />}
        </div>
      );
    }
    

    Using switch/case statement:
    If you have multiple conditions to handle, you can use a switch statement:

    function MyComponent({ status }) {
      switch (status) {
        case 'success':
          return <SuccessComponent />;
        case 'error':
          return <ErrorComponent />;
        default:
          return <DefaultComponent />;
      }
    }
    

    Using a function for conditional rendering:
    You can define a separate function to decide which component to render:

    function MyComponent({ condition }) {
      function getComponent() {
        if (condition === 'A') {
          return <ComponentA />;
        } else if (condition === 'B') {
          return <ComponentB />;
        } else {
          return <DefaultComponent />;
        }
      }
    
      return (
        <div>
          {getComponent()}
        </div>
      );
    }
    

    Select a strategy based on your unique use case and coding preferences. Utilising tools like React Router or Redux in some circumstances could also offer more effective solutions to manage complex conditional rendering scenarios. When selecting a method, always keep readability and maintainability of your code in mind.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search