React: Why does parent's componentDidMount gets called first, then child's?

Created on 26 Sep 2019  路  7Comments  路  Source: facebook/react

I thought it was always the case, that first, child's componentDidMount would be called, and then, parent's.

However, in this example: https://codesandbox.io/s/tender-jones-gpkz3

First parent's componentDidMount is called, then Child's (check the logs).

This happens _after_ I use this in child:

export default compose(
  withStyles(styles),
  withWidth()
)(Child);

Does anyone have explanation why this happens?

Question

All 7 comments

This has something to do with HOCs you're using recompose to wrap around Child. Remove them, and you'll see logs in the expected order.

Screen Shot 2019-09-26 at 8 38 04 AM

@bvaughn it seems it is withWidththat does it, it is from react Material UI library, maybe I should open issue there then...
I thought because of how react works, it should have never happened that childs CDM is called after parent, but maybe that HOC delays rendering or smth. like that..

but maybe that HOC delays rendering

That would be my guess. Not familiar with that project though.

@giorgi-m we plan to deprecate withWidth for https://material-ui.com/components/use-media-query/ (and withMediaQuery).

withWidth uses a two passes rendering strategy to handle server-side hydration. You can find an option to disable it in the API section. It will likely solve your problem.

However, you likely don't want to rely on the did mount call order.

@oliviertassinari

You can find an option to disable it in the API section. It will likely solve your problem.

if you drop link, I'd appreciate. Couldn't find.

if you replace it with useMediaQueryhook in the future, seems some features of material can't be used in class? would be nice if it stayed class compatible too ....

See the no ssr option in https://material-ui.com/customization/breakpoints/.

We had this class support feedback at a couple of occasion in the past. We will keep supporting class components as long as React does.

Thanks for the helpful added context, @oliviertassinari!

Was this page helpful?
0 / 5 - 0 ratings