ReactJS – getDerivedStateFromProps() Method

ReactJSWeb DevelopmentFront End Technology

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.

raja
Published on 18-Mar-2021 11:56:32
Advertisements