user8355916
user8355916

Reputation:

What happens when setState() function is called?

What does the setState() function run? Does it only run render()?

Upvotes: 22

Views: 10905

Answers (5)

Moslem Shahsavan
Moslem Shahsavan

Reputation: 1337

useState function has internal access to the behavior of its top-level function that is defined in it. it's not magic just use this reference.

So by calling setState function, it takes its higher level function and uses this for DOM comparison.

simple example create useState :)

function createState(val) {
    // `this` is top level reference (App function)
    const state = {
        call: 0,
        context: this,
        value: val
    };

    var _useState = function(callback){
        
         val = state.value = callback(val);
         
         state.call++;
         console.log("call: ", state.call)

         return val
    };

    return _useState;
};

function useState(value) {
  return [
       value,
       // pass null to access parent reference (App function)
       createState.bind(null, value)()
  ]; 
}

function App() {
    
  const  [val, setVal] =  useState(10)

  console.log(setVal(v => v+3));
  console.log(setVal(v => v+3));

}

App()

Upvotes: 0

RowanX
RowanX

Reputation: 1317

Just an update to this answer: https://stackoverflow.com/a/45273993/7310034 (since lifeCycle methods are now updated)

setState() will run functions in this order:

getDerivedStateFromProps()

shouldComponentUpdate()

render()

getSnapBeforeUpdate (if exists)

componentDidUpdate()

According to this: http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/

Upvotes: 0

Saurabh Kumar
Saurabh Kumar

Reputation: 127

The first thing React will do when setState is called is merged the object you passed into setState into the current state of the component. This will kick off a process called reconciliation. The end goal of reconciliation is to, in the most efficient way possible, update the UI based on this new state.

To do this, React will construct a new tree of React elements (which you can think of as an object representation of your UI). Once it has this tree, in order to figure out how the UI should change in response to the new state, React will diff this new tree against the previous element tree.

By doing this, React will then know the exact changes which occurred, and by knowing exactly what changes occurred, will able to minimize its footprint on the UI by only making updates where absolutely necessary.

The setState() will run functions in this order:

shouldComponentUpdate()

componentWillUpdate()

render()

componentDidUpdate()

If your component is receiving props it will run the componentWillRecieveProps() function with the above functions.

Upvotes: 4

Shubham Khatri
Shubham Khatri

Reputation: 281706

What does the setState() function run? Does it only run render()

No setState not only calls the render() function but after setState, the following lifecycle functions will run in order depending on what shouldComponentUpdate returns

if shouldComponentUpdate returns true(which is true by default).

1. shouldComponentUpdate
2. componentWillUpdate
3. render()
4. componentDidUpdate

if shouldComponentUpdate returns false(if you have a custom implementation)

1. shouldComponentUpdate

One more thing to know about setState is that, it only triggers the re-render for the current component and all its children(considering no implementation of shouldComponentUpdate for any of its children), Its doesn't trigger a re-render of the parent component and hence the reconcilation doesn't happen for the parent components but only for itself and its children.

A DEMO of what happens when setState is called.

class App extends React.Component {
    state = {
      count: 0
    }
    componentWillReceiveProps(nextProps) {
       console.log('componentWillReceiveProps parent');
    }
    shouldComponentUpdate() {
      console.log('shouldComponentUpdate parent');
      return true;
    }
    componentWillUpdate() {
      console.log('componentWillUpdate parent');
    }
    render() {
      console.log('render parent')
      return (
        <div>
            <Child count = {this.state.count}/>
            <button onClick={() => {
            console.log('callingsetState');this.setState((prevState) => ({count: prevState.count + 1}))}} >Increase</button>
        </div>
      )
    }
    componentDidUpdate() {
      console.log('componentDidUpdate parent')
    }
}
class Child extends React.Component {
    
    componentWillMount() {
      console.log('componentWillMount child');
    }
    componentDidMount() {
      console.log('componentDidMount child');
    }
    componentWillReceiveProps(nextProps) {
       console.log('componentWillReceiveProps child');
    }
    shouldComponentUpdate() {
      console.log('shouldComponentUpdate child');
      return true;
    }
    componentWillUpdate() {
      console.log('componentWillUpdate child');
    }
    render() {
      console.log('child')
      return (
        <div>
            <div>{this.props.count}</div>
        </div>
      )
    }
    componentDidUpdate() {
      console.log('componentDidUpdate child')
    }
}


ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

To add an explanation for the question that @poepje added on your question

What setState does?

setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses.

React has a very good documentation on this function here

You could also see the following answer on how setState works:

setState doesn't update the state immediately

Upvotes: 31

user8311804
user8311804

Reputation:

The setState() will run functions in this order:

shouldComponentUpdate()

componentWillUpdate()

render()

componentDidUpdate()

If your component is receiving props it will run the componentWillRecieveProps() function with the above functions.

Upvotes: 14

Related Questions