Geek Stocks
Geek Stocks

Reputation: 2030

What is React's earliest lifecycle event?

I have an object that I wish to install into the window.app variable as soon as possible, so that nested components can reference it as they mount. Now, outside of React, I would normally do this on the first line in window.onload() and I am wondering where the earliest possible spot is when using React which I am now learning.

I was using the App's componentDidMount method but the nested components fired their own componentDidMount first; App's componentDidMount seems to be last. Then I found this helpful lifecycle chart and I am now using App's constructor which is console logging before the nested components, so that's an improvement.

Is App's constructor the earliest spot we can write code?

Upvotes: 1

Views: 128

Answers (2)

Ashwin Valento
Ashwin Valento

Reputation: 1008

As suggested in the comments, Its not a good idea to directly set variable to the window object unless absolutely necessary.

Instead, a better approach would be to just pass the variable down as a prop.

As per your comment,

Well, its much more than a variable, its an object (class instance) which is modifying how localStorage will be used throughout the React app. Specifically, when a component interacts with localStorage, it will not call localStorage directly, but rather window.app.setStorage. You can see a demonstration of the idea here.

A better approach would be to just make a component for that which will have the set and get methods and use localstorage in the component. Import this component only where you need them. This will avoid using the window object all together and also keep your code much readable.

Upvotes: 0

Dhananjai Pai
Dhananjai Pai

Reputation: 6015

If you want it to execute as early as possible and does not depend on react, probably keep it outside the react ecosystem altogether and set it before the ReactDOM.render method that bootstraps the react application.

Upvotes: 3

Related Questions