Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will setState inside componentWillReceiveProps run before render?

Tags:

reactjs

The react docs mention that calls to setState are enqueued, and do not happen immediately. Does react make any guarantees that setState enqueued inside componentWillReceiveProps will execute before the next component render? Are either of these scenarios more likely than the other?

  1. props change > componentWillReceiveProps called > setState enqueued > setState runs > render (which includes new state)

  2. props change > componentWillReceiveProps called > setState enqueued > render > setState runs > re-rendered

Or, are both of these scenarios equally likely? Meaning does React not make any guarantees when setState will run relative to component lifecycle methods?

Here is a ES2015 code excerpt of my example:

import React from 'react';

class Widget extends React.Component {

  componentWillReceiveProps() {
    this.setState({foo: 'bar'});
  }

  render() {
    return <div>
      <a onClick={(e) => {
        e.preventDefault();
        this.props.triggerExternalPropsChange();
      }}>
        Click me to trigger new props
      </a>
    </div>;
  }
}

Where triggerExternalPropsChange passes new props to the Widget component.

like image 682
Evan Avatar asked Jun 28 '17 12:06

Evan


People also ask

Can we setState in componentWillReceiveProps?

componentWillReceiveProps() Safe to use setState ? Yes! This method is called whenever there is a change in the props. this method has an argument called nextProps can be compared with current props.

What happens when you call setState () inside render () method?

Because setState() function changes the state of the application and causing a change in the state called the render() function again. So if you write something like this then calling the function stack will go for infinity and application gets the crash.

What will happen if we call setState inside componentDidUpdate?

You may call setState() immediately in componentDidUpdate() but note that it must be wrapped in a condition like in the example above, or you'll cause an infinite loop. It would also cause an extra re-rendering which, while not visible to the user, can affect the component performance.

Does setState trigger render?

You may call setState() immediately in componentDidMount() . It will trigger an extra rendering, but it will happen before the browser updates the screen.


1 Answers

The only reason componentWillReceiveProps exists is to give the component an opportunity to setState. So yes, any state you set synchronously in it will be processed together with the new props. There won’t be two renders in this case, just one.

like image 170
Dan Abramov Avatar answered Oct 31 '22 08:10

Dan Abramov