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

@k1sul1 this guide forbids async/await currently, but either way, the rule has already been disabled.

setState is perfectly fine in componentDidMount, per https://github.com/airbnb/javascript/issues/684#issuecomment-340598319 and https://github.com/airbnb/javascript/commit/44dbd0bdc41d08eb5de8ad698099ae44240f4b0d - so no further comments on this issue are needed.

ljharb avatar Jan 05 '18 18:01 ljharb

@ljharb about the rule having been disabled, setState still triggers no-did-mount-state even after ugrading these packages. Am I missing something?

    "eslint": "^4.14.0",
    "eslint-config-airbnb": "^16.1.0",

Sowed avatar Jan 07 '18 05:01 Sowed

@Sowed you're not missing anything; https://github.com/airbnb/javascript/commit/44dbd0bdc41d08eb5de8ad698099ae44240f4b0d has not yet been released. Wait for the next (major) version.

ljharb avatar Jan 07 '18 06:01 ljharb

Doing setState in componentDidMount will cause a visible render flash.

For those still referring to this thread, it's worth pointing out this is no longer the case:

Calling setState() in this method will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render() will be called twice in this case, the user won’t see the intermediate state

https://reactjs.org/docs/react-component.html#componentdidmount

penx avatar Apr 16 '18 16:04 penx

This has not been released yet or am I missing something?

eluchsinger avatar May 24 '18 18:05 eluchsinger

@eluchsinger nope, not yet - you can check that https://github.com/airbnb/javascript/commit/44dbd0bdc41d08eb5de8ad698099ae44240f4b0d is only in master and no released tags.

ljharb avatar May 24 '18 18:05 ljharb

@ljharb @penx I find the language of the docs for componentDidMount() confusing. The method is invoked after the DOM is updated ("component...inserted into the tree") but you can setState immediately in componentDidMount() and essentially re-update the DOM again (now twice) "before the browser updates the screen". How is that possible? Perhaps you can update the DOM multiple times in one tick and the screen won't update until after the tick. Meanwhile, I gather, you can do things like measure the new DOM nodes, still in the same tick, before those DOM nodes are on the screen. Just guessing.

benkermode avatar May 04 '19 17:05 benkermode

Because setState doesn’t update the DOM, it asks react to queue up a dom change - react batches them together.

ljharb avatar May 04 '19 18:05 ljharb

@ljharb you're saying setting a state variable in a component constructor, then modifying it componentDidMount, will be batched together and executed as a single DOM change? I thought componentDidMount executed after a DOM change (namely component mounting). Then again, when the docs say "inserted into the tree" (for componentDidMount) I understand that to mean the DOM, but I don't think it's clear. The docs say that cDM can be used to measure the DOM, which certainly sounds like the DOM is already modified. Further, I understand "render" in react to mean create react elements in the virtual DOM, as opposed to DOM modification, as opposed to browser paint. But I find it difficult to ascertain exactly when these three things happen exactly in the lifecycle. I appreciate your comments on these issues!

benkermode avatar May 04 '19 19:05 benkermode

Not will be, might be. You’re right tho, that cDM does run after the first DOM update, so setState in cDM will result in at least two updates total.

ljharb avatar May 04 '19 20:05 ljharb

@ljharb okay, then I understand it to mean that you can modify the DOM multiple times in one tick, and then the browser will paint the current (last) state.

benkermode avatar May 04 '19 20:05 benkermode

For anyone interested there's some more discussion of it here: https://twitter.com/dan_abramov/status/981712092611989509?lang=en. Though I'd love to find more info on it.

benkermode avatar May 05 '19 12:05 benkermode

If your server requests take time you don't want to site around with a blank page. Async componentDidMount is the exact correct place to put server requests. Even if you get a page flash, that is your update coming back from the server. This error makes not sense because there is no better alternative.

nickjuntilla avatar Jun 21 '19 19:06 nickjuntilla

@nickjuntilla whether cDM is async or not is immaterial; I agree that server requests belong there since that's the first chance you get when using SSR to do browser-only things - hence this issue being closed in https://github.com/airbnb/javascript/issues/684#issuecomment-340598319.

ljharb avatar Jun 21 '19 19:06 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.

componentWillMount is depricated, I don't think it's a best place to api call and setState.

VinayKrMittal avatar Jun 02 '21 11:06 VinayKrMittal