Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If component returns null in its render function, why componentDidMount is triggered?

I've been using React for a while, but today I started wondering about one thing.

Why componentDidMount method is fired even though my render function returns null?

From the docs:

componentDidMount() is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.

As I understand it correctly: component returns null, so that there's nothing to mount in the DOM tree and componentDidMount should not be fired.

like image 528
TheOpti Avatar asked Aug 13 '18 12:08

TheOpti


1 Answers

componentDidMount() will fire exactly after render()! so you're saying that your render function returns null, which means render function executes!

Proof:

If you put a console.log inside your render function, exactly before return (what I do most of time for checking stuff like state updation or checking if current component receives props from parent component) you will see that log result in the console, which means that javascript executes the render.

It doesn't matter what it will render, null or hundred lines of jsx

like image 157
amdev Avatar answered Sep 25 '22 17:09

amdev