ReactJS – componentWillUpdate() Method

ReactJSWeb DevelopmentFront End Technology

In this article, we are going to see how to execute a function before 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 before the component is updated or when the state or props passed to the component changes. Don’t call setState() method in this function. This method will not be invoked if shouldComponentUpdate() methods return false.

Note: This method is now deprecated.

Syntax

UNSAFE_componentWillUpdate(nextProps, nextState)

Example

In this example, we will build a color changing React application which calls the componentWillUpdate method when the component is updated in the DOM tree.

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_componentWillUpdate(nextProps, nextState) {
      console.log('Component will be updated soon');
   }
   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:46:56

Advertisements