Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which kinds of initialization is more appropriate in constructor vs componentWillMount?

Tags:

reactjs

If I have a React component that requires some setup (e.g. for timers, or WebAudio API, etc), I'm having trouble deciding whether the initialization should go in constructor or componentWillMount. Is there any advantages or disadvantages to either one? It's not clear to me which one is the better place for this.

I Googled around a bit to see if anyone had discussed the differences between constructor and componentWillMount but I couldn't find anything.

EDIT: Redux and any asynchronous functions should not be part of the equation.

like image 769
ffxsam Avatar asked Jul 01 '16 05:07

ffxsam


People also ask

When should I use componentDidMount vs componentWillMount?

componentDidMount() is only called once, on the client, compared to componentWillMount() which is called twice, once to the server and once on the client. It is called after the initial render when the client received data from the server and before the data is displayed in the browser.

Why is componentWillMount unsafe?

These methods are considered “unsafe” because the React team expect code that depends on these methods to be more likely to have bugs in future versions of React. Depending on the objective of the code, you can remove the use of componentWillMount entirely with other lifecycle methods.

Should we use componentWillMount?

As a general rule don't use componentWillMount at all (if you use the es6 class syntax). use the constructor method instead. This life-cycle method is good for a sync state initialization. componentDidMount in the other hand is good for async state manipulation.

Which runs first constructor or componentDidMount?

constructor will be called pre-render and componentDidMount post-render. The componentWillMount method is called right before a component mounts or the render method is called.


2 Answers

Normally the only thing you do in the constructor is assign your initial this.state if your component is stateful. You should not do anything else in the constructor.

componentWillMount is generally unnecessary. I would say in most cases its use is an anti-pattern. One reason people use it is for updating the state from an external source one last time before rendering but technically assigning it in the constructor is equivalent. The only minor convenience it affords is that you can setState inside it but you can’t inside the constructor.

For any side effects (data fetching or DOM manipulation) you should use componentDidMount.

like image 176
Dan Abramov Avatar answered Oct 11 '22 17:10

Dan Abramov


If you want to call some flux action (for ajax calls) use componentWillMount or componentDidMount.

You can initialize state in constructor

like image 29
Piyush.kapoor Avatar answered Oct 11 '22 17:10

Piyush.kapoor