search
HomeWeb Front-endCSS TutorialThe Circle of a React Lifecycle

The Circle of a React Lifecycle

React components go through different stages in their application lifecycle, although what happens behind the scenes may not be obvious.

These stages include:

  • Mount
  • renew
  • uninstall
  • Error handling

Each stage has a corresponding method at which specific actions can be performed on components. For example, when fetching data from the network, you might want to call a function that handles API calls in componentDidMount() method (available in the mount phase).

Understanding different lifecycle approaches is crucial for the development of React applications, as it allows us to trigger operations accurately when needed without being confused with other operations. This article will cover each lifecycle, including the methods available and the types of scenarios we use them.

Mounting phase

Think of mounts as the initial stage of the component life cycle. The component did not exist before the mount occurred - it just flashed through the DOM until the mount occurred and connected it as part of the document.

Once the component is mounted, we can take advantage of many methods: constructor() , render() , componentDidMount() , and static getDerivedStateFromProps() . Each method has its own purpose, let's take a look in order.

constructor()

constructor() method is required when setting states directly on the component to bind methods together. It looks like this:

 // Once the input component starts mounting...
constructor(props) {
  // ...set some props...
  super(props);
  // ...In this case, it is a blank username...
  this.state = {
    username: ''
  };
  // ...then bind a method that handles input changes this.handleInputChange = this.handleInputChange.bind(this);
}

It is important to know that constructor is the first method called when creating a component. The component has not been rendered (coming soon), but the DOM already knows it and we can hook it to it before it renders. So this is not where we call setState() or introduce any side effects, because the component is still in the build phase!

I've written a tutorial on refs before and one thing I noticed is that when using React.createRef() , you can set ref in constructor . This is reasonable, because refs is used to change values ​​without props or have to re-render the component with updated values:

 constructor(props) {
  super(props);
  this.state = {
    username: ''
  };
  this.inputText = React.createRef();
}

render()

render() method is where the component's mark is displayed on the front end. The user can see and access it at this time. If you've ever created a React component, you're already familiar with it - even if you don't realize it - because it requires output tags.

 class App extends React.Component {
  // During the mount process, please render the following content!
  render() {
    Return (
      <div>
        <p>Hello World!</p>
      </div>
    )
  }
}

But that's not the whole purpose of render() ! It can also be used to render component arrays:

 class App extends React.Component {
  render () {
    Return [
      <h2 id="JavaScript-Tools">JavaScript Tools</h2> ,
      <frontend></frontend>,
      <backend></backend>
    ]
  }
}

Even component fragments:

 class App extends React.Component {
  render() {
    Return (
      <react.fragment><p>Hello World!</p></react.fragment>
    )
  }
}

We can also use it to render components outside the DOM hierarchy (similar to React Portal):

 // We are creating a portal that allows components to move class Portal extends React.Component {
  // First, we create a div element constructor() {
    super();
    this.el = document.createElement("div");
  }

  // After mount, let's append the child element of the component componentDidMount = () => {
    portalRoot.appendChild(this.el);
  };

  // If the component is removed from the DOM, then we also remove its child elements componentWillUnmount = () => {
    portalRoot.removeChild(this.el);
  };

  // Ah, now we can render the component and its child elements render() as needed {
    const { children } = this.props;
    return ReactDOM.createPortal(children, this.el);
  }
}

Of course render() can render numbers and strings...

 class App extends React.Component {
  render () {
    return "Hello World!"
  }
}

And null or boolean values:

 class App extends React.Component {
  render () {
    return null
  }
}

componentDidMount()

Does the name componentDidMount() indicate its meaning? This method is called after the component is mounted (i.e. connected to the DOM). In another tutorial I wrote about getting data in React, this is where you want to make a request to the API to get data.

We can use your fetch method:

 fetchUsers() {
  fetch(`https://jsonplaceholder.typicode.com/users`)
    .then(response => response.json())
    .then(data =>
      this.setState({
        users: data,
        isLoading: false,
      })
    )
  .catch(error => this.setState({ error, isLoading: false }));
}

Then call the method in the componentDidMount() hook:

 componentDidMount() {
  this.fetchUsers();
}

We can also add event listeners:

 componentDidMount() {
  el.addEventListener()
}

Very concise, right?

static getDerivedStateFromProps()

This is a bit verbose name, but static getDerivedStateFromProps() is not as complicated as it sounds. It is called before render() method of the mount phase and before the update phase. It returns an object to update the status of the component, or null if there is no content to be updated.

To understand how it works, let's implement a counter component that will set a specific value for its counter state. This status will only be updated when the value of maxCount is higher. maxCount will be passed from the parent component.

This is the parent component:

 class App extends React.Component {
  constructor(props) {
    super(props)

    this.textInput = React.createRef();
    this.state = {
      value: 0
    }
  }

  handleIncrement = e => {
    e.preventDefault();
    this.setState({ value: this.state.value 1 })
  };

  handleDecrement = e => {
    e.preventDefault();
    this.setState({ value: this.state.value - 1 })
  };

  render() {
    Return (
      <react.fragment><p>Max count: { this.state.value }</p>
           
          -
        <counter maxcount="{this.state.value}"></counter></react.fragment>
    )
  }
}

We have a button to increase the value of maxCount , which we pass to Counter component.

 class Counter extends React.Component {
  state={
    Counter: 5
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    if (prevState.counter 
        <p>Count: {this.state.counter}</p>

      
    )
  }
}

In the Counter component, we check if counter is smaller than maxCount . If so, we set counter to the value of maxCount . Otherwise, we do nothing.

Update phase

An update phase occurs when the component's props or state changes. Like mounts, updates also have their own set of available methods, which we will introduce next. That is, it is worth noting that render() and getDerivedStateFromProps() will also fire at this stage.

ShouldComponentUpdate()

When the state or props of the component change, we can use shouldComponentUpdate() method to control whether the component should be updated. This method is called before rendering occurs and when state and props are received. The default behavior is true . To re-render every time the state or props change, we do this:

 shouldComponentUpdate(nextProps, nextState) {
  return this.state.value !== nextState.value;
}

When false is returned, the component will not be updated, but instead calls render() method to display the component.

getSnaphotBeforeUpdate()

One thing we can do is capture the state of the component at some point in time, which is what getSnapshotBeforeUpdate() is designed for. It is called after render() but before committing any new changes to the DOM. The return value is passed as the third parameter to componentDidUpdate() .

It takes the previous state and props as parameters:

 getSnapshotBeforeUpdate(prevProps, prevState) {
  // ...
}

In my opinion, there are few use cases for this approach. It is a lifecycle method that you may not use often.

componentDidUpdate()

Add componentDidUpdate() to the method list, where the name roughly says everything. If the component is updated, then we can use this method to hook it at this time and pass it to the component's previous props and state.

 componentDidUpdate(prevProps, prevState) {
  if (prevState.counter !== this.state.counter) {
    // ...
  }
}

If you have ever used getSnapshotBeforeUpdate() , you can also pass the return value as a parameter to componentDidUpdate() :

 componentDidUpdate(prevProps, prevState, snapshot) {
  if (prevState.counter !== this.state.counter) {
    // ....
  }
}

Uninstallation phase

We almost see the opposite of the mount phase here. As you might expect, the uninstall occurs when the component is cleared from the DOM and is no longer available.

We only have one method here: componentWillUnmount()

This is called before the component is uninstalled and destroyed. This is where we want to perform any necessary cleanup after the component leaves, such as removing event listeners that might be added in componentDidMount() , or clearing the subscription.

 // Delete the event listener componentWillUnmount() {
  el.removeEventListener()
}

Error handling phase

There may be problems in the component, which may cause errors. We've been using error boundaries for a while to help solve this problem. This error boundary component uses some methods to help us deal with possible errors.

getDerivedStateFromError()

We use getDerivedStateFromError() to catch any errors thrown from the child component, and then we use it to update the state of the component.

 class ErrorBoundary extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      hasError: false
    };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  render() {
    if (this.state.hasError) {
      Return (
        <h1 id="Oops-something-went-wrong">Oops, something went wrong :(</h1>
      );
    }

    return this.props.children;
  }
}

In this example, when an error is thrown from the child component, the ErrorBoundary component will show "Oh, some problem has occurred".

componentDidCatch()

While getDerivedStateFromError() is suitable for updating the state of a component in the event of side effects such as error logging, we should use componentDidCatch() because it is called during the commit phase, at which time the DOM has been updated.

 componentDidCatch(error, info) {
  // Log errors to service}

Both getDerivedStateFromError() and componentDidCatch() can be used in the ErrorBoundary component:

 class ErrorBoundary extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      hasError: false
    };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    // Log errors to service}

  render() {
    if (this.state.hasError) {
      Return (
        <h1 id="Oops-something-went-wrong">Oops, something went wrong :(</h1>
      );
    }

    return this.props.children;
  }
}

This is the life cycle of React components!

It's a cool thing to understand how React components interact with DOM. It's easy to think that some "magic" will happen, and then something will appear on the page. But the life cycle of React components shows that this madness is orderly, and it aims to give us a lot of control over what happens from the time the component reaches the DOM to the time it disappears.

We cover a lot of things in a relatively short space, but hopefully this gives you a good idea of ​​how React handles components and what capabilities we have at each stage of processing. If you are not clear about anything introduced here, feel free to ask any questions and I'd love to do my best to help!

The above is the detailed content of The Circle of a React Lifecycle. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Next Level CSS Styling for CursorsNext Level CSS Styling for CursorsApr 23, 2025 am 11:04 AM

Custom cursors with CSS are great, but we can take things to the next level with JavaScript. Using JavaScript, we can transition between cursor states, place dynamic text within the cursor, apply complex animations, and apply filters.

Worlds Collide: Keyframe Collision Detection Using Style QueriesWorlds Collide: Keyframe Collision Detection Using Style QueriesApr 23, 2025 am 10:42 AM

Interactive CSS animations with elements ricocheting off each other seem more plausible in 2025. While it’s unnecessary to implement Pong in CSS, the increasing flexibility and power of CSS reinforce Lee's suspicion that one day it will be a

Using CSS backdrop-filter for UI EffectsUsing CSS backdrop-filter for UI EffectsApr 23, 2025 am 10:20 AM

Tips and tricks on utilizing the CSS backdrop-filter property to style user interfaces. You’ll learn how to layer backdrop filters among multiple elements, and integrate them with other CSS graphical effects to create elaborate designs.

SMIL on?SMIL on?Apr 23, 2025 am 09:57 AM

Well, it turns out that SVG's built-in animation features were never deprecated as planned. Sure, CSS and JavaScript are more than capable of carrying the load, but it's good to know that SMIL is not dead in the water as previously

'Pretty' is in the eye of the beholder'Pretty' is in the eye of the beholderApr 23, 2025 am 09:40 AM

Yay, let's jump for text-wrap: pretty landing in Safari Technology Preview! But beware that it's different from how it works in Chromium browsers.

CSS-Tricks Chronicles XLIIICSS-Tricks Chronicles XLIIIApr 23, 2025 am 09:35 AM

This CSS-Tricks update highlights significant progress in the Almanac, recent podcast appearances, a new CSS counters guide, and the addition of several new authors contributing valuable content.

Tailwind's @apply Feature is Better Than it SoundsTailwind's @apply Feature is Better Than it SoundsApr 23, 2025 am 09:23 AM

Most of the time, people showcase Tailwind's @apply feature with one of Tailwind's single-property utilities (which changes a single CSS declaration). When showcased this way, @apply doesn't sound promising at all. So obvio

Feeling Like I Have No Release: A Journey Towards Sane DeploymentsFeeling Like I Have No Release: A Journey Towards Sane DeploymentsApr 23, 2025 am 09:19 AM

Deploying like an idiot comes down to a mismatch between the tools you use to deploy and the reward in complexity reduced versus complexity added.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),