CSFundamental
Published in

CSFundamental

Day 12: Lifecycle methods in React continue

we will see how to use getDerivedStateFromProps in React to update the props and state of the component.

Updating

Updating is the process of changing the state or props of components and update changes to nodes already in the DOM. An update can be caused by changes to props or state. These methods are called in the following order when a component is being re-rendered:

A.) static getDerivedStateFromProps

This is invoked right before calling the render method, both on the initial mount and on subsequent updates. IT should return an object to update the state, or null to update nothing. This method exists for rare use cases where the state depends on changes in props over time. This method doesn’t have access to the component instance. As this a static method, this keyword is not available inside this method.

create a new project

$ create-react-app day-12$ cd day-12$ npm start

Add Student.js and Marks.js into your src folder. The Marks.js will be the child component of Student.js.

add the following code to Student.js

import React, {Component} from 'react';import Marks from './Marks';export default class Student extends Component {constructor(){super();//we are passing this state to our child (Marks) as props.this.state = {roll: 101};}clickHandle = () =>{console.log('button clicked')this.setState({roll:102})};render() {console.log("student component rendered")//the state above defined will passed as prop atttribute//of Mark componentreturn (<div><Marks roll={this.state.roll} /><button onClick={this.clickHandle} >Change</button></div>)}}

Mark.js

import React, {Component} from 'react';export default class Marks extends Component {
constructor(props) {super(props);this.state = {mroll: this.props.roll}}static getDerivedStateFromProps(props, state) { console.log("Get Derived Ran") console.log(props.roll) console.log(state.mroll) console.log(props, state) if(props.roll !== state.mroll){ return {mroll: props.roll} }return null}render() {console.log("marks component rendered")return (<div><h1>{this.state.mroll}</h1></div>)}}
before pressing the button
after pressing the button

so, what is going on here?

In our Student.js file, we have a property roll as a state. It means we can alter the value of the roll by using setState.

remember, we can’t do like this:

this.state.roll = 102  ❌this.setState({roll:102}) ✅

the state will be updated with a button click. So, we placed an event handler, clickHandle ().

And in the render method, we are passing our prop ( this.state.roll) to the child component ( Marks.js )

Student.js has only one output in the console, “student component rendered”, before we press our button.

Now, let’s see what is going on in the Marks.js.

we have passed the props of Student to Marks’s constructor and stored in the property mroll.

now, we have placed a method getDerivedStateFromProps before our render method. We have placed our logic inside of this method

if(props.roll !== state.mroll) 
{
return {mroll: props.roll}
}

the props coming from Student is compared to our current state of Marks component.

now, before we click the button,

props.roll = state.mroll

after, we pressed the button, the state of Student ( roll) changed its value to 102

now,
props.roll != state.mroll

and in the render method, we are logging, console.log(“marks component rendered”).

That should be all for getDerivedStateFromProps() method. In the next lesson, we will see shouldComponentUpdate() method.

Photo by Pakata Goh on Unsplash

--

--

--

From Web Development to Machine Learning, we will put a lot of free materials for anyone who wants to learn to code.

Recommended from Medium

Basics of Flexbox — 1

Writing WordPress REST API Endpoints Like Laravel Code

Controlling the Full-Screen Mode

Netflix on Fullscreen Mode

Glitch Write-Up

Why we strayed from our middleware stack for a micro-services framework called Steve

Steve, the marmot, holding a jar of TypeScript components

Understanding ‘this’ keyword in javascript

Simplify Your Life With React!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Saranjeet Singh

Saranjeet Singh

I write tutorials on Python, JavaScript, React, and Django. I write for InPlainEnglish and TheStartUp .

More from Medium

5 important tips, to become a (Frontend) Software-Engineer

Productive tools can be observed

How to use Nodemon in Loopback 4 NodeJs Project

Creating web apps: the tale of a millennial JS developper