DocumentationRulesprefer-read-only-props

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: stringname: 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: stringname}</JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div>;
}
import React from "react";
 
interface Props {
  Props.name: stringname: string;
}
 
function function Example(props: Props): React.JSX.ElementExample(props: Propsprops: Props) {
  //            - A function component's props should be read-only.
  return <JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div>{props: Propsprops.Props.name: stringname}</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: stringname: string }) {
return <JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div>{
props: {
    readonly name: string;
}
props
.name: stringname}</JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div>;
}
import React from "react";
 
interface Props {
  readonly Props.name: stringname: string;
}
 
function function Example(props: Props): React.JSX.ElementExample(props: Propsprops: Props) {
  return <JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div>{props: Propsprops.Props.name: stringname}</JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div>;
}

Further Reading