Sam Sam - 1 year ago 121
React JSX Question

Setting values in componentWillMount

Is it a good or a bad idea to set some values in

method in a React component?

Say, I have a controlled component that is linked to an object. I receive some values through props and need to set them in the object. It looks something like this:

class MyComponent extends Component {

constructor(props) {

componentWillMount() {

// I receive "color" through props and need to set it
// in my object which is done through an action

render() {
// Some stuff here

Trying to determine the best time/place to set this value. Ultimately, I need the value in
and receive the value through props.

Trying to see if handling this in
is a good idea or not.

Answer Source

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 before render(), 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download