2023-06-30 13:44:20 +00:00

107 lines
2.4 KiB
Plaintext

== Why is this an issue?
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.
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.
[source,javascript]
----
function Component() {
function NestedComponent() { // Noncompliant: NestedComponent should be moved outside Component
return <div />;
}
return (
<div>
<NestedComponent />
</div>
);
}
----
[source,javascript]
----
function Component() {
return (
<div>
<OtherComponent footer={ () => <div /> } /> { /* Noncompliant: Component is created inside prop */ }
</div>
);
}
----
[source,javascript]
----
class Component extends React.Component {
render() {
function UnstableNestedComponent() { // Noncompliant: NestedComponent should be moved outside Component
return <div />;
}
return (
<div>
<UnstableNestedComponent />
</div>
);
}
}
----
You should refactor your code to define a component independently, passing props if needed.
[source,javascript]
----
function OutsideComponent(props) {
return <div />;
}
function Component() {
return (
<div>
<OutsideComponent />
</div>
);
}
----
[source,javascript]
----
function Component() {
return <OtherComponent footer={ <div /> } />;
}
----
[source,javascript]
----
class Component extends React.Component {
render() {
return (
<div>
<OtherComponent />
</div>
);
}
}
----
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>
);
}
----
== Resources
* 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]