How should I alternate componentWillMount()?

constructor is not the right place for performing some actions. Because it will hold other operations until it’s finished.

componentDidMount is the right choice because it’s an asynchronous function so that actions are run in the background and there’ll be no hamper in the UI rendering.


Here’s a list that you can choose when to use between constructor and componentDidMount:

constructor

Do:

  • initialize state
  • bind event handlers

If you don’t initialize a state and you don’t bind methods, you don’t need to implement the constructor.

Don’t:

Avoid introducing any side-effects or subscriptions. Do not set state by using setState() in the constructor.

componentDidMount

Do:

  • initialization that requires DOM nodes
  • load data from a remote endpoint (where to instantiate the network request)
  • set up any subscriptions (don’t forget to unsubscribe in componentWillUnmount())

You may also be interested to read the comment from the creator of react, Dan Abramov:

I won’t like to wait for the component to be mounted to dispatch an ajax call to fulfill the component data dependencies. I would like to do it as soon as possible, like in the constructor, not even in componentWillMount.

If it’s an async request, it won’t be fulfilled by the time the component mounts anyway, regardless of where you fire it. This is because JS is single threaded, and the network request can’t “come back” and be handled while we are still rendering. So the difference between firing it earlier and later is often negligible.

You’re right that it matters in some rare cases though and for those cases it might make sense to break the recommendation. But you should be extra cautious as state can update before mounting, and if your data depends on state, you might have to refetch in that case. In other words: when in doubt, do it in componentDidMount.

The specific recommendation to avoid side effects in the constructor and Will* lifecycles is related to the changes we are making to allow rendering to be asynchronous and interruptible (in part to support use cases like this better). We are still figuring out the exact semantics of how it should work, so at the moment our recommendations are more conservative. As we use async rendering more in production we will provide a more specific guidance as to where to fire the requests without sacrificing either efficiency or correctness. But for now providing a clear migration path to async rendering (and thus being more conservative in our recommendations) is more important.


For further interest, you may also visit this post.

Leave a Comment