I am online
← Back to Articles

Using Object Literals Instead of Switch Case in React

ReactjsApril 27, 2024

Bad Code 👎:

switch (props.type) {
  case "ADMIN":
    return <Admin />;
  case "USER":
    return <User />;
  default:
    return <NotFound />;
}

The switch statement is verbose and can be less readable, especially with many cases. It also includes all components in the initial bundle, potentially increasing the bundle size unnecessarily.

Good Code 👍:

const componentMap = {
  ADMIN: Admin,
  USER: User,
  NOT_FOUND: NotFound,
};

const Component = componentMap[props.type] || componentMap.NOT_FOUND;
return <Component />;

Using an object literal improves readability and maintainability. The default case is handled using a fallback with ||.

Better Code 👌:

const componentMap = {
  ADMIN: React.lazy(() => import("@/components/Admin")),
  USER: React.lazy(() => import("@/components/User")),
  NOT_FOUND: React.lazy(() => import("@/components/NotFound")),
};

const Component = componentMap[props.type] || componentMap.NOT_FOUND;
return (
  <React.Suspense fallback={<div>Loading...</div>}>
    <Component />
  </React.Suspense>
);

This approach uses dynamic imports with React.lazy to load components only when needed, reducing the initial bundle size. React.Suspense is used to handle the loading state.