Skip to main content

react/noDidMountSetState

prevent usage of setState in componentDidMount

ESLint Equivalent: no-did-mount-set-state

Examples

Invalid

class Hello extends React.Component {
	componentDidMount() {
		this.setState({
			name: 'John'
		});
	}
}

 file.tsx:3:2 lint/react/noDidMountSetState ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

  Avoid calling this.setState in the componentDidMount method.

    1class Hello extends React.Component {
    2  componentDidMount() {
  > 3    this.setState({
         ^^^^^^^^^^^^^
    4      name: 'John'
    5    });

  Updating state after mounting causes a second render that can cause
    visual layout thrashing.


class Hello extends React.Component {
	componentDidMount() {
		foo();
		this.setState({
			name: 'John'
		});
	}
}

 file.tsx:4:2 lint/react/noDidMountSetState ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

  Avoid calling this.setState in the componentDidMount method.

    2  componentDidMount() {
    3    foo();
  > 4    this.setState({
         ^^^^^^^^^^^^^
    5      name: 'John'
    6    });

  Updating state after mounting causes a second render that can cause
    visual layout thrashing.


class Hello extends Component {
	componentDidMount() {
		this.setState({
			name: 'John'
		});
	}
}

 file.tsx:3:2 lint/react/noDidMountSetState ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

  Avoid calling this.setState in the componentDidMount method.

    1class Hello extends Component {
    2  componentDidMount() {
  > 3    this.setState({
         ^^^^^^^^^^^^^
    4      name: 'John'
    5    });

  Updating state after mounting causes a second render that can cause
    visual layout thrashing.


class Hello extends Component {
	componentDidMount() {
		foo();
		this.setState({
			name: 'John'
		});
	}
}

 file.tsx:4:2 lint/react/noDidMountSetState ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

  Avoid calling this.setState in the componentDidMount method.

    2  componentDidMount() {
    3    foo();
  > 4    this.setState({
         ^^^^^^^^^^^^^
    5      name: 'John'
    6    });

  Updating state after mounting causes a second render that can cause
    visual layout thrashing.

Valid

class Hello extends React.Component {
	componentDidMount() {
		if (condition) {
			this.setState({
				name: 'John'
			});
		}
	}
}
class Hello extends React.Component {
	componentDidMount() {
		condition && this.setState({
			name: 'John'
		});
	}
}
class Hello extends React.Component {
	componentDidMount() {
		condition ? this.setState({
			name: 'John'
		}) : undefined;
	}
}