- 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 – getDerivedStateFromProps() Method
In this article, we are going to see how to execute a function before the component is rendered.
This method is called before the rendering or before any updation of the component. This method is majorly used to update the state, before the rendering of the component, which depends upon the props received by the component. This method is called on every rerendering of the component.
Syntax
static getDerivedStateFromProps(props, state)
Parameters
props − Props passed to component
state − Previous state of component
Example
In this example, we will build a React application which will fetch the list of users and on clicking the 'fetch user' button, the Show component will get placed in the DOM and before rendering this component, getDerivedStateFromProps method is called which updates the state according to the props passed to it.
App.jsx
import React from 'react'; class App extends React.Component { constructor() { super(); this.state = { show: false, }; } render() { return ( <div> <h1>User List</h1> <h3>Username: Rahul</h3> <button onClick={() => this.setState({ show: true })}> Fetch Users </button> {this.state.show ? <Show email="qwerty@gmail.com" /> : null} </div> ); } } class Show extends React.Component { constructor() { super(); this.state = { email: '', }; } static getDerivedStateFromProps(props, state) { console.log('getDerivedStateFromProps method is called'); return { email: props.email }; } render() { return ( <div> <h3>Email: {this.state.email}</h3> </div> ); } } export default App;
Output
This will produce the following result.