javascript icon indicating copy to clipboard operation
javascript copied to clipboard

Why no setState in componentDidMount?

Open SimenB opened this issue 10 years ago • 35 comments

This is less of an issue and more of a question on how you handle things.

React docs says to put ajax-requests in componentDidMount. But I would also like to cancel the request in componentWillUnmount as that data is not needed if the component isn't there. And to do so, I need a reference to the promise created in componentDidMount. I thought to achieve this by putting it on state, like so:

componentDidMount() {
  this.setState({ serverRequest: this.props.fetcData() });
}

componentWillUnmount() {
  const { serverRequest } = this.state;

  if (serverRequest.isPending()) serverRequest.cancel();
}

(This is using bluebird btw, not native promises)

And this works, but the linter complains about the setState-call in componentDidMount.

I tracked down the issue where the rule was added (#345 & #346), and while the OP states that it follows your style guide, I can't find any reference to that rule in your docs.

So, my question is: Do you have any other way of keeping around references to async stuff created in componentDidMount such as ajax-requests, setTimeouts etc to be able to clean them up in componentWillUnmount? Or should I just disable the rule for that particular line?

SimenB avatar Jan 17 '16 18:01 SimenB

Why not put the setState call in componentWillMount? That would be the inverse of componentWillUnmount

ljharb avatar Jan 17 '16 20:01 ljharb

As the docs state that they belong in componentDidMount:

If you want to integrate with other JavaScript frameworks, set timers using setTimeout or setInterval, or send AJAX requests, perform those operations in this method.

SimenB avatar Jan 17 '16 20:01 SimenB

Touché :-) according to https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-did-mount-set-state.md, "Updating the state after a component mount will trigger a second render() call and can lead to property/layout thrashing."

However, since setState uses ===, i'm not sure if it's the best place to put a promise. What about an instance property?

ljharb avatar Jan 17 '16 21:01 ljharb

Just go this.serverRequest = ...?

SimenB avatar Jan 17 '16 21:01 SimenB

Sure. You'll want to make sure it's managed in the appropriate places, in case props change and whatnot, but otherwise that seems like it would be fine.

ljharb avatar Jan 17 '16 21:01 ljharb

Assigning to this works perfectly, and it is indeed buggy to use state. Thanks for the help!

SimenB avatar Jan 17 '16 22:01 SimenB

Ref facebook/react#5870

SimenB avatar Jan 17 '16 22:01 SimenB

@SimenB Can you elaborate on this.serverRequest = ...?

ericgrosse avatar Aug 10 '16 01:08 ericgrosse

@ericgrosse you can see the full example in the React docs: https://facebook.github.io/react/tips/initial-ajax.html Anything beyond that?

SimenB avatar Aug 10 '16 07:08 SimenB

I lost "this" inside of componentDidMount() where I ran a Stomp (ActiveMQ) topic listener. Inside that listener "this" became undefined. An uneducated trick that worked was to save "this" into a variable "thus" before entering that listener and I could use it inside the message handler doing stuff such as "thus.forceUpdate()" and similar.

ghost avatar Oct 07 '16 00:10 ghost

@mobimation or you could use an arrow function, and just use this directly

ljharb avatar Oct 07 '16 00:10 ljharb

Thanks @ljharb will try

ghost avatar Oct 07 '16 00:10 ghost

@SimenB I don't understand either! The eslint-plugin-react says

Prevent usage of setState in componentDidMount (no-did-mount-set-state).

Anyone can explain?

mrdulin avatar Dec 01 '16 06:12 mrdulin

Doing setState in componentDidMount will cause a visible render flash.

However, when doing server-rendering, anything that requires a browser environment must go in componentDidMount, since that runs client-only, but componentWillMount runs on both client and server.

This is an OK rule to disable.

ljharb avatar Dec 01 '16 07:12 ljharb

If this is an OK rule to disable, is the benefit really worth the inconvenience of the overrides? I would not consider it a general "best practice" to not use setState in componentDidMount.

If you have problematic render flashes you can work around that with various methods, and these methods often will not include moving setState from componentDidMount, but another fix, leaving you with a fix as well as the eslint-disable.

jacobrask avatar Mar 06 '17 13:03 jacobrask

There is also a scene that you must change your state depending on the what dom looks like. As a result, you must detect the dom element after mounting, which means you have to write the this.setState in componentDidMount.

zhaotai avatar Aug 15 '17 03:08 zhaotai

I don't think this rule should be enabled by default. As the docs state:

Calling setState() in this method will trigger an extra rendering, but it is guaranteed to flush during the same tick. This guarantees that even though the render() will be called twice in this case, the user won’t see the intermediate state.

So it causes no visible side-effects.

Use this pattern with caution because it often causes performance issues.

This could justify configuring it as a warning, but certainly not as an error.

It can, however, be necessary for cases like modals and tooltips when you need to measure a DOM node before rendering something that depends on its size or position.

And it can be necessary.

AndrewPrifer avatar Oct 30 '17 21:10 AndrewPrifer

It's definitely necessary for server rendering; I'm going to reopen this and change the default.

ljharb avatar Oct 30 '17 22:10 ljharb

I've spent so long time because I have 'this.setState' on componentDidMount. It didn't work so I moved it to componentWillMount and now it's working.

benevbright avatar Dec 17 '17 14:12 benevbright

I don't think that this rule makes any sense when using async/await.

Is there another, smarter way to do this?

  async componentDidMount() {
    try {
      const response = await wpQuery();
      const { headers, posts } = response;

      this.setState({
        posts,
        maxPages: headers['x-wp-totalpages'],
        maxPosts: headers['x-wp-total'],
      });
    } catch (error) {
        this.setState({
          error: 'Things went wrong, and the logic for error handling is irrelevant',
        });
      }
    }
  }

If it were a synchronous function, I'd understand a warning, and I'd probably want to see that warning.

k1sul1 avatar Jan 05 '18 12:01 k1sul1