Kuldeep Saxena
Kuldeep Saxena

Reputation: 2003

React: Previous props are not correct in componentDidUpdate

The use-case is to define a callback prop and need to compare its value in componentDidUpdate and based on that do some action. But previous props in the componentDidUpdate are similar to the new props.

Here is a code sandbox link where it can be seen.

Upvotes: 1

Views: 345

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281686

The reason the value in componentDidUpdate is same because you are calling a function from parent which returns you the state value and since the sstate value is updated by the time you call the function, it returns you the new value.

If however you copy the state value to a variable in render and then then use that inside your function, it will return you the old value since its then bound by closure i.e you are using a variable from lexical scope of the function when its created and when the component re-renders a new function reference is created with the updated value of state in lexical scope

render() {
    const val = this.state.myCallback;
    return (
      <div className="App">
        <button onClick={this.updateCallback} type="button">
          UPDATE CALLBACK
        </button>
        <Child myCallback={() => val} />
      </div>
    );
  }

Edit FORM VALUES

Upvotes: 2

Related Questions