DEV Community

loading...

Discussion on: Conditionally render react components in cleaner way

Collapse
dungmidside profile image
Dung Tran

A downside of enum solution is all the component will be compiled even it doesn't need to rendered

Collapse
ridays2001 profile image
Riday

So, we have to compromise on performance to get clean code?

Collapse
ms_yogii profile image
Yogini Bende Author

Not really. Check what Luke have shared!

Thread Thread
ridays2001 profile image
Riday

Hmm... Makes sense... Nice article!

Collapse
ms_yogii profile image
Yogini Bende Author

We can use enums more creatively and achieve performance as well. Luke have shown a really good example for that below.

Collapse
lukeshiru profile image
△ LUKE知る

Not necessarily. It can be changed to look something like this:

import { createElement } from "react";

export const RoleSettings = {
  admin: AdminSettings,
  user: UserSettings,
  guest: GuestSettings,
};

export const Settings = ({ userRole, username }) => (
  <div>
    <h1>Settings</h1>
    <p>{createElement(RoleSettings[userRole], { username })}</p>
  </div>
);
Enter fullscreen mode Exit fullscreen mode

or this:

export const roleSettings = {
  admin: AdminSettings,
  user: UserSettings,
  guest: GuestSettings,
};

export const Settings = ({ userRole, username }) => {
  const RoleSettings = roleSettings[userRole];
  return (
    <div>
      <h1>Settings</h1>
      <p>
        <RoleSettings username={username} />
      </p>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

In both snippets you make use of the "enum solution", and only create the instance of the component you're actually using :D

Collapse
ms_yogii profile image
Yogini Bende Author

Yeah. That's a good way to optimise when you are dealing with large components! We can modify the enum solutions more creatively to achieve both performance as well as simplicity of code.