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.
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.
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.
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.
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.
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
.
If you want to call some flux action (for ajax calls) use componentWillMount or componentDidMount.
You can initialize state in constructor
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With