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 {
name: string;
}
class Example extends React.Component<ExampleProps, ExampleState> {
componentDidUpdate() {
this.setState({ name: "John" });
// ^^^^^^^^^^^^^^^^^^^^^^^^^^
// - Do not call `this.setState` in `componentDidUpdate` outside of functions, such as callbacks.
}
render() {
return <div>Hello {this.state.name}</div>;
}
}