prefer-read-only-props
💭 This rule requires type information.
Rule category
Correctness
What it does
This rule enforces that function components props are read-only.
Why is this good?
Props are read-only snapshots in time: every render receives a new version of props. You can’t change props. This rule enforces that you don’t accidentally mutate props.
Examples
Failing
import React from "react";
function function Example(props: {
name: string;
}): React.JSX.Element
Example(props: {
name: string;
}
props: { name: string
name: string }) {
// - A function component's props should be read-only.
return <JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>
div>{props: {
name: string;
}
props.name: string
name}</JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>
div>;
}
import React from "react";
interface Props {
Props.name: string
name: string;
}
function function Example(props: Props): React.JSX.Element
Example(props: Props
props: Props) {
// - A function component's props should be read-only.
return <JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>
div>{props: Props
props.Props.name: string
name}</JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>
div>;
}
Passing
import React from "react";
function function Example(props: {
readonly name: string;
}): React.JSX.Element
Example(props: {
readonly name: string;
}
props: { readonly name: string
name: string }) {
return <JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>
div>{props: {
readonly name: string;
}
props.name: string
name}</JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>
div>;
}
import React from "react";
interface Props {
readonly Props.name: string
name: string;
}
function function Example(props: Props): React.JSX.Element
Example(props: Props
props: Props) {
return <JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>
div>{props: Props
props.Props.name: string
name}</JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>
div>;
}