3 ms·
I mildly disagree. componentWillMount() is slightly superior to the constructor, though only for very specific situations[0]. I would agree that for the vast ma
by AnkhMorporkian 9y ago
I mildly disagree. componentWillMount() is slightly superior to the constructor, though only for very specific situations[0]. I would agree that for the vast majority of people who use ES6, the difference basically doesn't exist, but there is a real reason to use componentWillMount instead of the constructor.
0: https://github.com/reactjs/react-redux/issues/129 https://github.com/reactjs/react-redux/issues/129
Edit: You might call dispatching in a constructor an anti-pattern (or having any side-effects at all), but quite a few people do it and it can cause very subtle bugs that aren't entirely reproducible.
- steve_taylor 9y agoYeah, if you dispatch in a constructor and the effect is synchronous, it's going to setState somewhere and React will complain, whereas if you do it from componentWillMount, maybe React won't complain, but I'm not sure. My understanding is that componentWillMount was needed for React.createClass, but not so much ES6 classes. It seems a bit weird to be calling setState on a component within the context of another component being created. As far as I'm concerned, setState should only ever be called from an event handler, such as user input, an endpoint returning a response, or a timer event.
- AnkhMorporkian 9y agoI'm not sure how familiar with it you are, but that's kinda a result of flux/redux architecture. There's a global state that things are passed props to. If there is some change triggered as the result of a component being mounted, say a globalish "there's now a tooltip active", that may modify components including the component that triggered the change. That's probably a simplistic example, but it really does happen.