Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why and when to use componentDidMount in react js?

I was going through the react tutorial and I'm confused as to why componentDidMount is used?

like image 303
Sai Charan Avatar asked Dec 18 '22 22:12

Sai Charan


2 Answers

I think the documentation covers it well enough:

Mounting: componentDidMount

void componentDidMount()

Invoked once, only on the client (not on the server), immediately after the initial rendering occurs. At this point in the lifecycle, you can access any refs to your children (e.g., to access the underlying DOM representation). The componentDidMount() method of child components is invoked before that of parent components.

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.

like image 165
Felix Kling Avatar answered Dec 31 '22 01:12

Felix Kling


One really useful way to use componentDidMount is for AJAX requests.

So, imagine a situation where you want to get a list of Comments for an Article. After the component is created you may want to go retrieve the list of comments from the server and then display them to the user.

Here's an example (from the React tutorial): https://facebook.github.io/react/docs/tutorial.html#updating-state

like image 42
patrick Avatar answered Dec 31 '22 01:12

patrick