
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
ReactJS componentWillUpdate Method
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.