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)

Hot Topics

CSS blocks page rendering because browsers view inline and external CSS as key resources by default, especially with imported stylesheets, header large amounts of inline CSS, and unoptimized media query styles. 1. Extract critical CSS and embed it into HTML; 2. Delay loading non-critical CSS through JavaScript; 3. Use media attributes to optimize loading such as print styles; 4. Compress and merge CSS to reduce requests. It is recommended to use tools to extract key CSS, combine rel="preload" asynchronous loading, and use media delayed loading reasonably to avoid excessive splitting and complex script control.

Autoprefixer is a tool that automatically adds vendor prefixes to CSS attributes based on the target browser scope. 1. It solves the problem of manually maintaining prefixes with errors; 2. Work through the PostCSS plug-in form, parse CSS, analyze attributes that need to be prefixed, and generate code according to configuration; 3. The usage steps include installing plug-ins, setting browserslist, and enabling them in the build process; 4. Notes include not manually adding prefixes, keeping configuration updates, prefixes not all attributes, and it is recommended to use them with the preprocessor.

Theconic-gradient()functioninCSScreatescirculargradientsthatrotatecolorstopsaroundacentralpoint.1.Itisidealforpiecharts,progressindicators,colorwheels,anddecorativebackgrounds.2.Itworksbydefiningcolorstopsatspecificangles,optionallystartingfromadefin

TocreatestickyheadersandfooterswithCSS,useposition:stickyforheaderswithtopvalueandz-index,ensuringparentcontainersdon’trestrictit.1.Forstickyheaders:setposition:sticky,top:0,z-index,andbackgroundcolor.2.Forstickyfooters,betteruseposition:fixedwithbot

The scope of CSS custom properties depends on the context of their declaration, global variables are usually defined in :root, while local variables are defined within a specific selector for componentization and isolation of styles. For example, variables defined in the .card class are only available for elements that match the class and their children. Best practices include: 1. Use: root to define global variables such as topic color; 2. Define local variables inside the component to implement encapsulation; 3. Avoid repeatedly declaring the same variable; 4. Pay attention to the coverage problems that may be caused by selector specificity. Additionally, CSS variables are case sensitive and should be defined before use to avoid errors. If the variable is undefined or the reference fails, the fallback value or default value initial will be used. Debug can be done through the browser developer

Mobile-firstCSSdesignrequiressettingtheviewportmetatag,usingrelativeunits,stylingfromsmallscreensup,optimizingtypographyandtouchtargets.First,addtocontrolscaling.Second,use%,em,orreminsteadofpixelsforflexiblelayouts.Third,writebasestylesformobile,the

To create an intrinsic responsive grid layout, the core method is to use CSSGrid's repeat(auto-fit,minmax()) mode; 1. Set grid-template-columns:repeat(auto-fit,minmax(200px,1fr)) to let the browser automatically adjust the number of columns and limit the minimum and maximum widths of each column; 2. Use gap to control grid spacing; 3. The container should be set to relative units such as width:100%, and use box-sizing:border-box to avoid width calculation errors and center them with margin:auto; 4. Optionally set the row height and content alignment to improve visual consistency, such as row

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.
