Paul Redmond
Paul Redmond

Reputation: 3296

React - Run function if property of an object passed as a prop has changed

Is there a way to run a function after a component has updated but only if a property of that object (as a prop!) has changed?

Original object:

const employees = {
   employee1: {
      name: "John",
      age: "24"
   },
   employee2: {
      name: "Jane",
      age: "20"
   }
}

Updated object (note, John's age has changed):

const employees = {
   employee1: {
      name: "John",
      age: "25"
   },
   employee2: {
      name: "Jane",
      age: "20"
   }
}

Inside child component getting employees as a prop:

   componentWillReceiveProps(nextProps) {
      const {employees} = this.props;

      if (nextProps.employees !== employees) {
         // Run function...
      }
   }

Upvotes: 1

Views: 783

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118271

Use componentDidUpdate callback hook. It has access to (prevProps, prevState, ..).

For equality test I would use _.isEqual method as it performs a deep comparison between two values to determine if they are equivalent.

componentDidUpdate(prevProps) {
  const {
    employees
  } = this.props;

  if (!_.isEqual(prevProps.employees, employees)) {
    // Run function...
  }
}

Note: Look componentDidUpdate method is called after the render() is executed. So in case you want to dismiss the rendering of the component based on props validation, then shouldcomponentupdate will be correct choice.

Upvotes: 1

Related Questions