no-set-state-in-component-did-update
Rule category
Suspicious.
What it does
Disallows calling this.setState in componentDidUpdate 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.componentDidUpdate(): voidCalled immediately after updating occurs. Not called for the initial render.
The snapshot is only present if
{@link
getSnapshotBeforeUpdate
}
is present and returns non-null.componentDidUpdate() {
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 `componentDidUpdate` 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>;
}
}