- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 – componentWillReceiveProps() Method
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.