no-set-state-in-component-did-mount
Rule category
Suspicious.
What it does
Disallows calling this.setState
in componentDidMount
outside of functions, such as callbacks.
Why is this bad?
Updating the state after a component mount will trigger a second render()
call and can lead to property/layout thrashing.
Examples
Failing
import React from "react";
interface ExampleProps {}
interface ExampleState {
ExampleState.name: string
name: string;
}
class class Example
Example extends React.class React.Component<P = {}, S = {}, SS = any>
Component<ExampleProps, ExampleState> {
Example.componentDidMount(): void
Called immediately after a component is mounted. Setting state here will trigger re-rendering.componentDidMount() {
this.React.Component<ExampleProps, ExampleState, any>.setState<"name">(state: ExampleState | ((prevState: Readonly<ExampleState>, props: Readonly<ExampleProps>) => Pick<ExampleState, "name"> | ExampleState | null) | Pick<...> | null, callback?: (() => void) | undefined): void
setState({ name: string
name: "John" });
// - Do not call `this.setState` in `componentDidMount` outside of functions, such as callbacks.
}
Example.render(): React.JSX.Element
render() {
return <JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>
div>Hello {this.React.Component<ExampleProps, ExampleState, any>.state: Readonly<ExampleState>
state.name: string
name}</JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>
div>;
}
}