26
votes

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.

2
Per the documentation, this should go in componentDidMount: facebook.github.io/react/docs/… "If you want to....set timers...or setInterval...perform those operations in this method." - lux

2 Answers

29
votes

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.

1
votes

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

You can initialize state in constructor