DEV Community

Cover image for Nested Components - A bad practice? - ReactJS
Sanjampreet Singh
Sanjampreet Singh

Posted on • Edited on

Nested Components - A bad practice? - ReactJS

Is creating a component inside another components a bad practice? Isn't it a cool way to code in ReactJs? Doesn't ReactJs allows us to create nested components?

To answer, creating components inside of other components may seem convenient at first, but it can lead to several problems:

export default function ParentComponent(props) {
  function InnerComponent() {
    // ...
  }

  return (
    <>
      <InnerComponent />
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

To begin with, nested components become tightly coupled with the parent component, making them less reusable. Inner components cannot be exported and reused; instead, they are passed down as props to other components, resulting in less modular code.

Additionally, creating components within components can lead to performance issues. The declaration function for the inner component will be recreated on each render cycle of the parent component. This can result in the application losing its previous state and slowing down, especially in larger projects.

While ReactJs does not explicitly prohibit the creation of nested components, it is generally preferable to avoid creating components within other components. Keeping components in their own files, on the other hand, can ensure modularity and reusability.

This can be avoided by creating a separate component in another file and importing it in another component.

// InnerComponent.js
const InnerComponent = (props) => {
  // ...
}

export default InnerComponent;
Enter fullscreen mode Exit fullscreen mode
// ParentComponent.js
import InnerComponent from './InnerComponent';

const ParentComponent = (props) => {
  return (
    <>
      <InnerComponent />
    </>
  );
}

export default ParentComponent;
Enter fullscreen mode Exit fullscreen mode

For example, if you have a button component that is used throughout the application, it is best to keep it in a separate file so that it can be easily imported and reused throughout the app.

Or you can create a component outside the component, for example some popup form that has a limited scope in the application.

function InnerComponent(props) {
  return (
    // ...
  );
}

export default function ComponentTwo(props) {
  return (
    <>
      <InnerComponent />
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

So, if you're working on a React project, keep your components organised in their own files to maximise reusability and performance.

Top comments (0)