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.
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.
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.
interface Props {
readonly name: string;
}
function Welcome(props: Props) {
return <div>Hello {props.name}</div>;
}