Rules
no-set-state-in-component-will-update

no-set-state-in-component-will-update

Rule category

Suspicious.

What it does

Disallows calling this.setState in componentWillUpdate 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.componentWillUpdate(): void
Called immediately before rendering when new props or state is received. Not called for the initial render. Note: You cannot call {@link Component.setState } here. Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate } or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps } prevents this from being invoked.
@deprecated16.3, use getSnapshotBeforeUpdate instead; will stop working in React 17@see{@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#reading-dom-properties-before-an-update}@see{@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path}
componentWillUpdate
() {
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 `componentWillUpdate` 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>; } }