2023-05-03 11:06:20 +02:00
== Why is this an issue?
2023-06-30 15:44:20 +02:00
React components should not be nested, as their state will be lost on each re-render of their parent component, possibly introducing bugs. This will also impact performance as child components will be recreated unnecessarily.
2022-11-28 12:42:10 +01:00
2023-06-30 15:44:20 +02:00
If the goal is to have the state reset, use a https://react.dev/learn/preserving-and-resetting-state#option-2-resetting-state-with-a-key[`key`] instead of relying on a parent state.
2022-11-28 12:42:10 +01:00
[source,javascript]
----
function Component() {
2023-06-30 15:44:20 +02:00
function NestedComponent() { // Noncompliant: NestedComponent should be moved outside Component
2022-11-28 12:42:10 +01:00
return <div />;
}
return (
<div>
2023-06-30 15:44:20 +02:00
<NestedComponent />
2022-11-28 12:42:10 +01:00
</div>
);
}
----
[source,javascript]
----
function Component() {
return (
<div>
2023-06-30 15:44:20 +02:00
<OtherComponent footer={ () => <div /> } /> { /* Noncompliant: Component is created inside prop */ }
2022-11-28 12:42:10 +01:00
</div>
);
}
----
[source,javascript]
----
class Component extends React.Component {
render() {
2023-06-30 15:44:20 +02:00
function UnstableNestedComponent() { // Noncompliant: NestedComponent should be moved outside Component
2022-11-28 12:42:10 +01:00
return <div />;
}
return (
<div>
<UnstableNestedComponent />
</div>
);
}
}
----
2023-06-30 15:44:20 +02:00
You should refactor your code to define a component independently, passing props if needed.
2022-11-28 12:42:10 +01:00
[source,javascript]
----
2023-06-30 15:44:20 +02:00
function OutsideComponent(props) {
2022-11-28 12:42:10 +01:00
return <div />;
}
function Component() {
return (
<div>
2023-06-30 15:44:20 +02:00
<OutsideComponent />
2022-11-28 12:42:10 +01:00
</div>
);
}
----
[source,javascript]
----
function Component() {
2023-06-30 15:44:20 +02:00
return <OtherComponent footer={ <div /> } />;
2022-11-28 12:42:10 +01:00
}
----
[source,javascript]
----
class Component extends React.Component {
render() {
return (
<div>
2023-06-30 15:44:20 +02:00
<OtherComponent />
2022-11-28 12:42:10 +01:00
</div>
);
}
}
----
2023-06-30 15:44:20 +02:00
Component creation is allowed inside component props only if prop name starts with `render`. Make sure you are calling the prop in the receiving component and not using it as an element.
[source,javascript]
----
function OtherComponent(props) {
return <div>{props.renderFooter()}</div>;
}
function Component() {
return (
<div>
<OtherComponent renderFooter={() => <div />} />
</div>
);
}
----
2023-05-03 11:06:20 +02:00
== Resources
2022-11-28 12:42:10 +01:00
2023-06-30 15:44:20 +02:00
* https://reactjs.org/docs/reconciliation.html#elements-of-different-types[React Documentation - Elements Of Different Types]
* https://react.dev/learn/preserving-and-resetting-state#option-2-resetting-state-with-a-key[React Documentation - Resetting state with a key]