-
Notifications
You must be signed in to change notification settings - Fork 56
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
8571c9d
commit 4c91b06
Showing
4 changed files
with
265 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,244 @@ | ||
--- | ||
Id: 1010 | ||
Title: React Lifecycle Methods | ||
Author: Soumyajit | ||
Tags: React Interview | ||
Topic: React | ||
Abstract: Lifecycle methods are series of events that happen throughout the birth, growth, and death of a React component. | ||
HeaderImage: /BL-1010/Header.jpg | ||
isPublished: true | ||
--- | ||
|
||
**Visual overview of topics covered in this tutorial** | ||
|
||
![Lifecycle](/BL-1010/Lifecycle.png) | ||
|
||
## What is the React component lifecycle? {#What-is-the-React-component-lifecycle} | ||
|
||
In React, components go through a lifecycle of events: | ||
|
||
- Mounting (adding nodes to the DOM) | ||
- Updating (altering existing nodes in the DOM) | ||
- Unmounting (removing nodes from the DOM) | ||
|
||
## Mounting lifecycle methods {#Mounting-lifecycle-methods} | ||
|
||
The mounting phase refers to the phase during which a component is created and inserted to the DOM. | ||
The following methods are called in order. | ||
|
||
- constructor() | ||
- static getDerivedStateFromProps() | ||
- render() | ||
- componentDidMount() | ||
|
||
### constructor() {#constructor} | ||
|
||
The constructor() is the very first method that is invoked before the component is mounted to the DOM. | ||
|
||
The constructor method is called before the component is mounted to the DOM. In most cases, you would initialize state and bind event handlers methods within the constructor method. | ||
|
||
Example of the constructor() React lifecycle method in action: | ||
|
||
``` | ||
const MyComponent extends React.Component { | ||
constructor(props) { | ||
super(props) | ||
this.state = { | ||
points: 0 | ||
} | ||
this.handlePoints = this.handlePoints.bind(this) | ||
} | ||
} | ||
``` | ||
|
||
### static getDerivedStateFromProps() {#static-getDerivedStateFromProps} | ||
|
||
Its main function is to ensure that the state and props are in sync for when it’s required. | ||
|
||
The basic structure of the static getDerivedStateFromProps() looks like this: | ||
|
||
``` | ||
static getDerivedStateFromProps(props, state) { | ||
//do stuff here | ||
} | ||
``` | ||
|
||
``` | ||
You can return an object to update the state of the component: | ||
static getDerivedStateFromProps(props, state) { | ||
return { | ||
points: 200 // update state with this | ||
} | ||
} | ||
Or you can return null to make no updates: | ||
static getDerivedStateFromProps(props, state) { | ||
return null | ||
} | ||
``` | ||
|
||
``` | ||
class App extends Component { | ||
state = { | ||
points: 10 | ||
} | ||
// ******* | ||
// NB: Not the recommended way to use this method. Just an example. Unconditionally overriding state here is generally considered a bad idea | ||
// ******** | ||
static getDerivedStateFromProps(props, state) { | ||
return { | ||
points: 1000 | ||
} | ||
} | ||
render() { | ||
return ( | ||
<div className="App"> | ||
<header className="App-header"> | ||
<img src={logo} className="App-logo" alt="logo" /> | ||
<p> | ||
You've scored {this.state.points} points. | ||
</p> | ||
</header> | ||
</div> | ||
); | ||
} | ||
} | ||
The 1000 comes from updating state within the static getDerivedStateFromProps method. | ||
``` | ||
|
||
### render() {#render} | ||
|
||
As the name suggests it handles the rendering of your component to the UI | ||
|
||
``` | ||
class Hello extends Component{ | ||
render(){ | ||
return <div>Hello {this.props.name}</div> | ||
} | ||
} | ||
``` | ||
|
||
The render() method returns JSX that is displayed in the UI. A render() can also return a null if there is nothing to render for that component. | ||
|
||
A render() method has to be pure with no side-effects. | ||
React requires that your render() is pure. Pure functions are those that do not have any side-effects and will always return the same output when the same inputs are passed. This means that you can not `setState() within a render()`. `You cannot modify the component state within the render().` | ||
|
||
### componentDidMount {#componentDidMount} | ||
|
||
After render is called, `the component is mounted to the DOM and the componentDidMount method is invoked.` | ||
|
||
This function is invoked immediately after the component is mounted to the DOM. | ||
|
||
You would use the componentDidMount lifecycle method to grab a DOM node from the component tree immediately after it’s mounted. | ||
|
||
**If you also want to make network requests as soon as the component is mounted to the DOM, this is a perfect place to do so.** | ||
|
||
``` | ||
componentDidMount() { | ||
this.fetchListOfTweets() // where fetchListOfTweets initiates a netowrk request to fetch a certain list of tweets. | ||
} | ||
``` | ||
|
||
**You could also set up subscriptions such as timers** | ||
|
||
``` | ||
// e.g requestAnimationFrame | ||
componentDidMount() { | ||
window.requestAnimationFrame(this._updateCountdown); | ||
} | ||
``` | ||
|
||
## Updating lifecycle methods {#Updating-lifecycle-methods} | ||
|
||
Whenever a change is made to the state or props of a React component, the component is rerendered. In simple terms, the component is updated. This is the updating phase of the React component lifecycle. | ||
|
||
- shouldComponentUpdate() | ||
- render() | ||
- getSnapshotBeforeUpdate() | ||
- componentDidUpdate() | ||
|
||
### shouldComponentUpdate() {#shouldComponentUpdate} | ||
|
||
In most cases, you’ll want a component to rerender when state or props changes. However, you do have control over this behavior. | ||
|
||
Within this lifecycle method, you can return a boolean true or false and control whether the component gets rerendered (e.g., upon a change in state or props). | ||
|
||
``` | ||
shouldComponentUpdate(nextProps, nextState) | ||
{ | ||
return this.props.title !== nextProps.title || | ||
this.state.input !== nextState.input | ||
} | ||
``` | ||
|
||
### render() {#render} | ||
|
||
After the shouldComponentUpdate method is called, render is called immediately afterward, depending on the returned value from shouldComponentUpdate, which defaults to true. | ||
|
||
### getSnapshotBeforeUpdate() {#getSnapshotBeforeUpdate} | ||
|
||
The getSnapshotBeforeUpdatelifecycle method stores the previous values of the state after the DOM is updated. getSnapshotBeforeUpdate() is called right after the render method. | ||
|
||
``` | ||
getSnapshotBeforeUpdate(prevProps, prevState) { | ||
} | ||
``` | ||
|
||
Here’s the important thing: the value queried from the DOM in getSnapshotBeforeUpdate refers to the `value just before the DOM is updated, even though the render method was previously called`. | ||
|
||
`The getSnapshotBeforeUpdate React lifecycle method doesn’t work on its own. It is meant to be used in conjunction with the componentDidUpdate lifecycle method`. | ||
|
||
### componentDidUpdate() {#componentDidUpdate} | ||
|
||
The componentDidUpdate lifecycle method is invoked after the getSnapshotBeforeUpdate. As with the getSnapshotBeforeUpdate method it receives the previous props and state as arguments: | ||
|
||
``` | ||
componentDidUpdate(prevProps, prevState) { | ||
} | ||
``` | ||
|
||
However it also takes whatever value is returned from the getSnapshotBeforeUpdate lifecycle method is passed as the third argument to the componentDidUpdate method. | ||
|
||
``` | ||
componentDidUpdate(prevProps, prevState, snapshot) { | ||
} | ||
``` | ||
|
||
## Unmounting lifecycle method {#Unmounting-lifecycle-method} | ||
|
||
The following method is invoked during the component unmounting phase | ||
|
||
- componentWillUnmount() | ||
|
||
### componentWillUnmount() {#componentWillUnmount} | ||
|
||
The componentWillUnmount lifecycle method is invoked immediately before a component is unmounted and destroyed. This is the ideal place to perform any necessary cleanup such as clearing up timers, cancelling network requests, or cleaning up any subscriptions that were created in componentDidMount(). | ||
|
||
``` | ||
// e.g add event listener | ||
componentDidMount() { | ||
el.addEventListener() | ||
} | ||
``` | ||
|
||
``` | ||
// e.g remove event listener | ||
componentWillUnmount() { | ||
el.removeEventListener() | ||
} | ||
``` | ||
|
||
**References:** | ||
|
||
- React Lifecycle Methods A Deep Dive:- https://programmingwithmosh.com/javascript/react-lifecycle-methods/ | ||
- React lifecycle methods: An approachable tutorial with examples:- https://blog.logrocket.com/react-lifecycle-methods-tutorial-examples |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4c91b06
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Successfully deployed to the following URLs: