52 lines
2.0 KiB
Plaintext

== Why is this an issue?
React props should be read-only because it helps to enforce the principle of immutability in React functional components. By making props read-only, you ensure that the data passed from a parent component to a child component cannot be modified directly by the child component. This helps maintain a clear data flow and prevents unexpected side effects.
If props were mutable, child components could modify the props directly, leading to unpredictable behavior and making it harder to track down bugs. By enforcing read-only props, React promotes a more predictable and maintainable codebase. Additionally, read-only props enable performance optimizations in React's rendering process by avoiding unnecessary re-renders of components.
Overall, enforcing read-only props in React helps improve code reliability, maintainability, and performance.
[source,javascript,diff-id=1,diff-type=noncompliant]
----
interface Props {
name: string;
}
function Welcome(props: Props) { // Noncompliant: The component props are not read-only
return <div>Hello {props.name}</div>;
}
----
You should use TypeScript's utility type `Readonly` to make your functional component props read-only.
[source,javascript,diff-id=1,diff-type=compliant]
----
interface Props {
name: string;
}
function Welcome(props: Readonly<Props>) {
return <div>Hello {props.name}</div>;
}
----
Alternatively, you can use TypeScript's modifier `readonly` to mark all the props of your functional component individually as read-only.
[source,javascript,diff-id=1,diff-type=compliant]
----
interface Props {
readonly name: string;
}
function Welcome(props: Props) {
return <div>Hello {props.name}</div>;
}
----
== Resources
=== Documentation
* React Documentation - https://react.dev/learn/passing-props-to-a-component[Passing Props to a Component]
* TypeScript Documentation - https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype[Readonly<Type>]
* TypeScript Documentation - https://www.typescriptlang.org/docs/handbook/2/classes.html#readonly[readonly]