Table of Contents
Mounting phase
constructor()
render()
JavaScript Tools
componentDidMount()
static getDerivedStateFromProps()
Update phase
ShouldComponentUpdate()
getSnaphotBeforeUpdate()
componentDidUpdate()
Uninstallation phase
Error handling phase
getDerivedStateFromError()
Oops, something went wrong :(
componentDidCatch()
This is the life cycle of React components!
Home Web Front-end CSS Tutorial The Circle of a React Lifecycle

The Circle of a React Lifecycle

Apr 21, 2025 am 09:35 AM

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);
}
Copy after login

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();
}
Copy after login

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>
    )
  }
}
Copy after login

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>
    ]
  }
}
Copy after login

Even component fragments:

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

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);
  }
}
Copy after login

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

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

And null or boolean values:

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

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 }));
}
Copy after login

Then call the method in the componentDidMount() hook:

 componentDidMount() {
  this.fetchUsers();
}
Copy after login

We can also add event listeners:

 componentDidMount() {
  el.addEventListener()
}
Copy after login

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>
    )
  }
}
Copy after login

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>

      
    )
  }
}
Copy after login

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;
}
Copy after login

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) {
  // ...
}
Copy after login

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) {
    // ...
  }
}
Copy after login

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) {
    // ....
  }
}
Copy after login

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()
}
Copy after login

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;
  }
}
Copy after login

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}
Copy after login

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;
  }
}
Copy after login

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 of this Website
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

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Vue 3 Vue 3 Apr 02, 2025 pm 06:32 PM

It&#039;s out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

Building an Ethereum app using Redwood.js and Fauna Building an Ethereum app using Redwood.js and Fauna Mar 28, 2025 am 09:18 AM

With the recent climb of Bitcoin’s price over 20k $USD, and to it recently breaking 30k, I thought it’s worth taking a deep dive back into creating Ethereum

Can you get valid CSS property values from the browser? Can you get valid CSS property values from the browser? Apr 02, 2025 pm 06:17 PM

I had someone write in with this very legit question. Lea just blogged about how you can get valid CSS properties themselves from the browser. That&#039;s like this.

A bit on ci/cd A bit on ci/cd Apr 02, 2025 pm 06:21 PM

I&#039;d say "website" fits better than "mobile app" but I like this framing from Max Lynch:

Stacked Cards with Sticky Positioning and a Dash of Sass Stacked Cards with Sticky Positioning and a Dash of Sass Apr 03, 2025 am 10:30 AM

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.

Using Markdown and Localization in the WordPress Block Editor Using Markdown and Localization in the WordPress Block Editor Apr 02, 2025 am 04:27 AM

If we need to show documentation to the user directly in the WordPress editor, what is the best way to do it?

Comparing Browsers for Responsive Design Comparing Browsers for Responsive Design Apr 02, 2025 pm 06:25 PM

There are a number of these desktop apps where the goal is showing your site at different dimensions all at the same time. So you can, for example, be writing

Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Apr 05, 2025 pm 05:51 PM

Questions about purple slash areas in Flex layouts When using Flex layouts, you may encounter some confusing phenomena, such as in the developer tools (d...

See all articles