ReactJS – componentWillReceiveProps() Method

ReactJSWeb DevelopmentFront End Technology

In this article, we are going to see how to execute a function if the props passed to the component is updated in the DOM tree.

This method is used during the updating phase of the React lifecycle. This function is generally called if the props passed to the component change. It is used to update the state in response with the new received props. setState() method doesn’t generally call this method again.

Note: This method is now deprecated.

Syntax

UNSAFE_componentWillReceiveProps(nextProps)

Example

In this example, we will build a color-changing React application which will call the componentWillReceiveProps method when the props of the component are updated.

Our first component in the following example is App. This component is the parent of the ChangeName component. We are creating ChangeName separately and just adding it inside the JSX tree in our App component. Hence, only the App component needs to be exported.

App.jsx

import React from 'react';

class App extends React.Component {
   state = { color: 'green' };
   render() {
      setTimeout(() => {
         this.setState({ color: 'wheat' });
      }, 4000);
      return (
         <div>
            <h1>Tutorialspoint</h1>
            <ChangeName color={this.state.color} />
         </div>
      );
   }
}
class ChangeName extends React.Component {
   UNSAFE_componentWillReceiveProps(nextProps) {
      console.log('Component received new props', nextProps);
   }
   render() {
      console.log('ChangeName component is called');
      return (
         <div>
            <h1 style={{ color: this.props.color }}>Simply Easy Learning</h1>
         </div>
      );
   }
}
export default App;

Output

This will produce the following result.

raja
Published on 18-Mar-2021 11:43:34

Advertisements