Member-only story

React Basic — What goes in componentDidMount?

Marika Lam
1 min readJan 7, 2022

--

Photo by J K on Unsplash

When is componentDidMount called?

componentDidMount() is invoked immediately after a component is mounted. As the name suggests, after all the elements of the page is rendered correctly, this method is called.

What goes in componentDidMount?

  1. Here you may load a data from a remote endpoint. It is a good place to instantiate the network request.
  2. Here you may set up any subscriptions. If you do that, don’t forget to unsubscribe in componentWillUnmount().
  3. Here you may call setState() immediately.

Warning for #3: It 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. Use this pattern with caution because it often causes performance issues. In most cases, you should be able to assign the initial state in the constructor() instead.

Summary

Overall, all the AJAX requests and the DOM or state updates should be coded in the componentDidMount() method block. We can also set up all the major subscriptions here but to avoid any performance issues, always remember to unsubscribe them in the componentWillUnmount() method.

References

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

--

--

No responses yet