이 페이지는 아직 한국어로 제공되지 않으며 번역 작업 중입니다. 번역에 관한 질문이나 의견이 있으시면 언제든지 저희에게 연락해 주십시오.

Metadata

ID: jsx-react/no-nested-components

Language: JavaScript

Severity: Warning

Category: Best Practices

Description

In JavaScript, particularly when using React, it’s important to avoid nesting components inside other components. Components are meant to be reusable, independent, and encapsulated.

When components are nested, it could lead to unnecessary re-rendering and performance degradation, as the nested component is re-created every time the parent component renders.

To avoid this, define your components at the top level of your module and then use them inside other components by referencing their names. This way, the components are only created once and reused, leading to better performance and easier code management.

Non-Compliant Code Examples

function Foo() {
  function Bar() {
    return <h1> heading </h1>;
  }

  return (
    <>
      <Bar />
    </>
  );
}

function Test() {
  return (
    <div>
      <InnerTest footer={ () => <div /> } /> { }
    </div>
  );
}

class View extends React.Component {
  render() {
    function Nested() {
      return <h2> nested heading </h2>;
    }

    return (
      <div>
        <Nested />
      </div>
    );
  }
}

Compliant Code Examples

function Bar(props) {
  return <h1> heading </h1>;
}

function Foo() {
  return (
    <>
      <Bar />
    </>
  );
}

function Test() {
  return <InnerTest footer={ <div /> } />;
}

class View extends React.Component {
  render() {
    return (
      <div>
        <Nested />
      </div>
    );
  }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis

PREVIEWING: rtrieu/product-analytics-ui-changes