Is it a good or a bad idea to set some values in
componentWillMount()
class MyComponent extends Component {
constructor(props) {
super(props);
}
componentWillMount() {
// I receive "color" through props and need to set it
// in my object which is done through an action
this.props.actions.setColor(this.props.color);
}
render() {
return(
<div>
// Some stuff here
</div>
);
}
}
myObject
componentWillMount()
It's a bad idea if the call has side effects e.g updating a store. From the docs for componentWillMount
:
componentWillMount()
is invoked immediately before mounting occurs. It is called beforerender()
, therefore setting state synchronously in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method.
Also componentWillMount
may be called several times e.g. server side rendering. You should use componentDidMount
instead.
On the other hand if the call has no side effects, you should move the call to your constructor instead.