Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the re-render problem in React

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "how to solve the re-render problem in React". In the daily operation, I believe that many people have doubts about how to solve the re-render problem in React. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubt of "how to solve the re-render problem in React"! Next, please follow the editor to study!

Re-render?

First use my scaffolding:

Npm I ykj-cli-g ykj init Appcd. / appyarn yarn dev

Such a webpack5, TS and React project has been set up.

We currently have only one APP component, internal code:

Import Myy from'. / myy.jpg';function App () {console.log ('render') return (Welcome to Mingyuan Cloud-Cloud Space Front-end Universal Scaffold

Join us: 453089136@qq.com micro-front end, webpack5,TypeScript,React,vite has everything);} export default App

After refreshing the visit page, I found that the console only printed once.

OK, so let's get started, add some states, and add a button and SubApp component.

Import {useState} from 'react';import Myy from'. / myy.jpg';import SubApp from'. / SubApp'function App () {const [state, setState] = useState ("Peter"); return (welcome to open source cloud-cloud space front-end universal scaffolding

Join us: 453089136@qq.com micro-front-end, webpack5,TypeScript,React,vite has {setState ('follow official account: front-end peak')} > test button);} export default App / / SubApp component function SubApp ({state}) {console.log ('render') return {state}} export default SubApp

At this time, click the button and trigger another render.

After many clicks, we found that there is only one render, because each click at this time changes the value of state to

So, we try to turn state into an object.

Const [state, setState] = useState ({des: "Peter"}); {setState ({des: 'follow official account: front-end peak'})} > Test button

Something amazing happened, and every time I clicked to set the same state, it triggered the subcomponent render. -here comes the re-render problem. In fact, we all get the same state, but there is unnecessary render.

Wrong optimization

Many students mistakenly use PureComponent, useEffect and UseMemo in the process of using React.

Here we first introduce useEffect in the wrong way to transform SubApp

Import React, {useEffect, useState} from 'react';function SubApp ({state}) {const [data, setData] = useState ({}) useEffect (() = > {console.log (' render') setData (state)}, [state]) console.log ('render') return {data.des} export default SubApp

Here you can see that every click of the button is constantly render, the use of useEffect is unexpectedly invalid. This optimization is invalid ~

Here we will talk about the source code implementation of useEffect. In fact, a series of optimization methods, such as useEffect and PureComponent, mostly use the Object.is () algorithm.

MDN data address: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/is

Object.is

The Object.is () method determines whether two values are the same value.

Value1

The first value compared.

Value2

The second value being compared.

Return value

A Boolean type indicates whether two parameters are the same value.

Description

The Object.is () method determines whether two values are the same value. The two values are equal if the following conditions are met:

It's all undefined.

It's all null.

All true or false.

Are all strings of the same length and the same characters are arranged in the same order

Are all the same objects (meaning that each object has the same reference)

It's all numbers and

All + 0

All are-0

It's all NaN.

Or both are non-zero and non-NaN and have the same value

Different from the = = (en-US) operation. The = = operator casts variables on both sides (if they are not of the same type) before judging equality (the result of this behavior is to judge "" = = false as true), while Object.is does not cast values on both sides.

The operation is also different from the = = (en-US) operation. The = = operator (including the = = operator) treats the numbers-0 and + 0 as equal, while Number.NaN and NaN are not equal.

Rational use of useEffect to solve re-render

If Props passes in an object, then each update of React hooks generates a brand new object, which cannot be compared with the previous object through Object.is and is not equal each time. For example:

Const obj1 = {name: "peter"} const obj2 = {name: "peter"} console.log (Object.is (obj1, obj2, 'xx'))

The output of this code is always false, because obj1 and obj2 are reference objects with different addresses.

But if we do it another way:

Object.is (obj1.name, obj2.name)

So that you can compare normally and output ture forever.

So now we're going to use something like this in useEffect.

UseEffect (() = > {setData (state) console.log ('render')}, [state.des])

In this way, our useEffect internal callback will only be triggered once

Simple implementation of useEffect

The code copied online modifies the method of comparison:

Let _ deps;function useEffect (callback, dependencies) {const hasChanged = _ deps & &! dependencies.every ((el, I) = > Object.is (el, _ deps [I])) | | true; / / if dependencies does not exist, or if dependencies changes, execute callback if (! dependencies | | hasChanged) {callback (); _ deps = dependencies;}}

Implementation logic: traverse the incoming dependency, compare it with the value of the original dependency through the Object.is method, and execute callback if it is inconsistent.

At this point, the study on "how to solve the re-render problem in React" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report