Rules
no-set-state-in-component-did-mount

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: stringname: string;
}
 
class class ExampleExample 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): voidsetState({ name: stringname: "John" }); // - Do not call `this.setState` in `componentDidMount` outside of functions, such as callbacks. } Example.render(): React.JSX.Elementrender() { return <JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div>Hello {this.React.Component<ExampleProps, ExampleState, any>.state: Readonly<ExampleState>state.name: stringname}</JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div>; } }