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>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>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>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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

There are three ways to create a CSS loading rotator: 1. Use the basic rotator of borders to achieve simple animation through HTML and CSS; 2. Use a custom rotator of multiple points to achieve the jump effect through different delay times; 3. Add a rotator in the button and switch classes through JavaScript to display the loading status. Each approach emphasizes the importance of design details such as color, size, accessibility and performance optimization to enhance the user experience.

To deal with CSS browser compatibility and prefix issues, you need to understand the differences in browser support and use vendor prefixes reasonably. 1. Understand common problems such as Flexbox and Grid support, position:sticky invalid, and animation performance is different; 2. Check CanIuse confirmation feature support status; 3. Correctly use -webkit-, -moz-, -ms-, -o- and other manufacturer prefixes; 4. It is recommended to use Autoprefixer to automatically add prefixes; 5. Install PostCSS and configure browserslist to specify the target browser; 6. Automatically handle compatibility during construction; 7. Modernizr detection features can be used for old projects; 8. No need to pursue consistency of all browsers,

Themaindifferencesbetweendisplay:inline,block,andinline-blockinHTML/CSSarelayoutbehavior,spaceusage,andstylingcontrol.1.Inlineelementsflowwithtext,don’tstartonnewlines,ignorewidth/height,andonlyapplyhorizontalpadding/margins—idealforinlinetextstyling

Use the clip-path attribute of CSS to crop elements into custom shapes, such as triangles, circular notches, polygons, etc., without relying on pictures or SVGs. Its advantages include: 1. Supports a variety of basic shapes such as circle, ellipse, polygon, etc.; 2. Responsive adjustment and adaptable to mobile terminals; 3. Easy to animation, and can be combined with hover or JavaScript to achieve dynamic effects; 4. It does not affect the layout flow, and only crops the display area. Common usages are such as circular clip-path:circle (50pxatcenter) and triangle clip-path:polygon (50%0%, 100 0%, 0 0%). Notice

Setting the style of links you have visited can improve the user experience, especially in content-intensive websites to help users navigate better. 1. Use CSS's: visited pseudo-class to define the style of the visited link, such as color changes; 2. Note that the browser only allows modification of some attributes due to privacy restrictions; 3. The color selection should be coordinated with the overall style to avoid abruptness; 4. The mobile terminal may not display this effect, and it is recommended to combine it with other visual prompts such as icon auxiliary logos.

To create responsive images using CSS, it can be mainly achieved through the following methods: 1. Use max-width:100% and height:auto to allow the image to adapt to the container width while maintaining the proportion; 2. Use HTML's srcset and sizes attributes to intelligently load the image sources adapted to different screens; 3. Use object-fit and object-position to control image cropping and focus display. Together, these methods ensure that the images are presented clearly and beautifully on different devices.

Different browsers have differences in CSS parsing, resulting in inconsistent display effects, mainly including the default style difference, box model calculation method, Flexbox and Grid layout support level, and inconsistent behavior of certain CSS attributes. 1. The default style processing is inconsistent. The solution is to use CSSReset or Normalize.css to unify the initial style; 2. The box model calculation method of the old version of IE is different. It is recommended to use box-sizing:border-box in a unified manner; 3. Flexbox and Grid perform differently in edge cases or in old versions. More tests and use Autoprefixer; 4. Some CSS attribute behaviors are inconsistent. CanIuse must be consulted and downgraded.

The choice of CSS units depends on design requirements and responsive requirements. 1.px is used for fixed size, suitable for precise control but lack of elasticity; 2.em is a relative unit, which is easily caused by the influence of the parent element, while rem is more stable based on the root element and is suitable for global scaling; 3.vw/vh is based on the viewport size, suitable for responsive design, but attention should be paid to the performance under extreme screens; 4. When choosing, it should be determined based on whether responsive adjustments, element hierarchy relationships and viewport dependence. Reasonable use can improve layout flexibility and maintenance.
