Do you have trouble understanding the React lifecycle method and how to use it elegantly? Don’t worry, you’re not alone. When I first wrote the React app, I ran into so many situations that I had to take a step back and relearn the React lifecycle approach to keep developing. Before we start, I want you to know that the latest version of React has decided to remove some of the older, insecure lifecycle methods in React 17. In this blog post we will not learn about unsafe lifecycle methods that will be removed soon.

What is the React lifecycle method

You can think of the React lifecycle method as the sequence of events that the React component goes through from birth to death

Every component in React goes through life cycle events, which I tend to understand as a cycle of birth, growth, and death.

  • Mount (Mounting) – Component is born
  • Updating – Component growth
  • Unmounting (Unmounting) – Component dies

Now let’s begin to learn how this series of lifecycle events work.

Common React lifecycle methods

render()

The Render () method is the most common lifecycle method, and you’ll see it in all class components. This is because the Render () method is the only mandatory method in the React class component.

Here is a simple example of Redner () in React

class Hello extends Component {
	render() {
  	return <div>Hello {this.props.name}</div>}}Copy the code

As you can see above, the reder() method returns the JSX used to present the UI. A render() method can return a Boolean or NULL to indicate that everything is rendered.

The Render () method is a pure function with no side effects

React requires the render() function to be a pure function. A pure function means that it has no side effects and must return the same output with the same input. This means you can’t use setState() in render().

You can no longer modify component state in Redner () _ If you need to change state, you should do so in another lifecycle method. Keep render() pure anyway. In addition, keeping render() simple, clean and free of status updates improves the maintainability of your application.

componentDidMount()

Now that your component is mounted and ready, the next lifecycle method is componentDidMount().

ComponentDidMount is called when the component is mounted and ready. This is a good place to call your API if you need to load remote data.

Unlike Render (), componentDidMount() allows setState(), where calling setState() will update the state and cause a new render, but before the browser updates the UI. This is to ensure that the user does not see the UI refresh between two renders.

You can be incomponentDidMount()Modify component state, but use caution

Note: You are advised to use this mode with caution, as it may cause performance problems. The best action is to initialize the state in constructor(). React allows the use of setState() in this lifecycle method because special requirements such as tooltips, modals, etc. require DOM node positions to be measured before rendering.

componentDidUpdate()

This method is called as soon as an update occurs. The most common scenario is to update the DOM based on changes in props or state.

You can call setState() during this lifecycle, but be careful to determine if you need to call it based on changes in props and state. The use of toilet errors leads to an infinite loop of rendering.

You can go throughcomponentDidUpdate()Modify state, but use it with care

The following is a typical use case for this lifecycle approach

componentDidUpdate(prevProps) {
  
  // Notice the comparison here for props
	if (this.props.userName ! == prevProps.userName) {this.fetchData(this.props.userName); }}Copy the code

Note that in the previous example, we compared the current props to the previous props to see if the props has changed. If there is no change, the API will not be called. The same goes for state.

componentWillUnmont()

As the name suggests, this lifecycle method is only called before the component is unloaded and destroyed, and can be called in this method if you need to do some cleanup (such as cancel listening, clear timer, etc.).

You can’tcomponentWillUnmountChanging component state within a period (State)

This component will never be re-rendered because we cannot call setState() inside this method.

componentWillUnmount() {
	window.removeEventListener('resize'.this.resizeListener);
}
Copy the code

The typical cleanup here is to clear timers, cancel API calls, or clear caches.

Uncommon React lifecycle methods

In addition to the common React lifecycle methods that we now know about, React provides other lifecycle methods that are not commonly used or even used.

shouldComponentUpdate()

This lifecycle method is useful when you don’t want a component refresh due to changes in props or state. Any call to setState() defaults to re-rendering the component, and shouldComponenUpdate() can be used to tell React that the component is not affected by certain props or states.

Be careful when using this method; it exists only for performance optimization, and you can’t update the component state in shouldComponentUpdate().

Note: Most importantly, do not always rely on this method to prevent component rendering, which can cause some bugs

shouldComponentUpdate(nextProps, nextState) {
 return this.props.title ! == nextProps.title ||this.state.input ! == nextState.input }Copy the code

In the example shown above, this method should always return a Boolean value to determine whether to render the component.

static getDerivedStateFromProps()

This is the latest lifecycle approach from the React team.

This will be used to replace componentWillReceiveProps () more safe solution.

It will be called before render().

This is a static method, so you can’t access this. GetDerivedFromProps () returns an object depending on the props change to update the state, or it can return NULL to indicate that no state needs to be updated.

This method exists to solve the problem that the value of state of a component depends on props in some special cases.

static getDerivedStateFromProps(props, state) {
    if(props.currentRow ! == state.lastRow) {return {
        isScrollingDown: props.currentRow > state.lastRow,
        lastRow: props.currentRow,
      };
    }
    // Return null to indicate no change to state.
    return null;
  }
Copy the code

Note that this method is called every time a component renders.

A convenient scenario for using this method is the
component that compares the children before and after to determine which one will animate the entrance/entrance.

getSnapshotBeforeUpdate()

GetSnapshotBeforeUpdate () is another new React lifecycle method. This is a more secure alternative to componentWillUpdate().

getSnapshotBeforeUpdate(prevProps, prevState) {
    // ...
  }
Copy the code

This is called before the update, and the value returned from getSnapshotBeforeUpdate() is passed to componentDidUpdate().

Keep in mind that this method should be used sparingly or not at all.

Changing the window size during asynchronous rendering is a good place to use getSnapshotBeforeUpdate().

React component life cycle diagram

The followingThe chartShows the different React component lifecycle functions and their appropriate calls.

review

  • The React component lifecycle consists of three phases: Mounting, Updating, and Unmounting.
  • render()Is the most common lifecycle method
    • Pure functions
    • Not in therender()When modifying the state
  • componentDidMount()Is called after the component is mounted
    • You can change state here, but be careful
  • componentDidUpdate()Is called after the component is updated
    • You can change state here, but be careful
  • componentWillUnmount()Called only before the component is unloaded and destroyed
    • You can clean it up here
    • You can’t change state here
  • shouldComponentUpdate()Rarely used
    • This lifecycle method is useful when you don’t want a component refresh due to changes in props or state
    • It exists solely for performance optimization
  • There are two new lifecycle approachesgetDerivedStateFromProps()andgetSnapshotBeforeUpdate()
    • They are used only occasionally
    • They are used in fewer scenarios and are still under discussion, with more examples to follow

As address: programmingwithmosh.com/javascript/…