当前位置:网站首页>Use usedeferredvalue for asynchronous rendering
Use usedeferredvalue for asynchronous rendering
2022-07-02 02:41:00 【Code Taoist】
Recently, I am developing a complex application , I found my React The mental model is wrong . This is a simplified version of it :
const AppWithSynchronousRendering = () => {
const [counter, setCounter] = useState(0);
return (
<div className="App" style={AppStyle}>
<ExpensiveRenderComponent counter={counter} />
<BasicComponent counter={counter} />
<button onClick={() => setCounter(counter + 1)}>Increment</button>
</div>
);
}
It is generally accepted that , As long as the components prop change , It will immediately re render . So I hope to be here once counter
change ,<ExpensiveRenderComponent/>
and <BasicComponent/>
It will re render , Show their respective contents . Whereas <ExpensiveRenderComponent/>
Before displaying its contents, you need to do some processing that will affect the performance , I hope <BasicComponent/>
First render . But it's not : The two components are updated at the same time . let me put it another way ,<BasicComponent/>
wait for <ExpensiveRenderComponent/>
appear .
I spent quite a long time on this problem , Finally, I found out my React What is missing from the mental model . ad locum , We need to know more about React How rendering works .
React Rendering is synchronous
Whenever the state of a component changes ,React Will trigger the re rendering of the latter and all its sub components . There are three steps in this process :
- React First Calculation New caused by state change fictitious DOM. fictitious DOM Basically user interface Javascript Express , Equivalent to actual DOM. The only difference here is not to show virtual DOM, Therefore, the operation is faster .
- When calculating the new virtual DOM after ,React Will compare it with reality DOM Compare and update the actual changes . This process is called reconciliation.
- As a last step ,React Apply the changes to the actual DOM. This is called commit Stage .
Calculate new virtual DOM It means running the code of each component rendered due to state changes . therefore , The duration of this step is at least As long as it takes to calculate the most complex components .
In our example , Due to the same state change ,<ExpensiveRenderComponent/>
and <BasicComponent/>
To render .<ExpensiveRenderComponent/>
Some expensive calculations need to be performed , therefore React You must wait for it to complete before updating the actual DOM. in the meantime ,UI Become unresponsive .
So rendering is Sync Of . This behavior is also for Uniformity And designed .React Always re render components because the same state is updated at the same time . stay file This is well explained in :
This is meaningful in most cases . inconsistent UI Can cause confusion , And may mislead users .
One solution is to optimize the components that take the longest rendering time . But what if it's impossible ? This is it. React 18 Where it comes in handy !
React 18 Concurrent characteristics
React 18 On 2022 year 3 Published in , And introduced a powerful concurrent rendering function . Before , Rendering is synchronous , As our example shows : Each rendering component triggered by a state change must wait for all other components to be ready to update . Use React 18, Each state change can be given a different priority , You can even assign different priorities to each component rendering , As we will see . In short ,React 18 To enable the Asynchronous rendering .
Let's see how the new hook useDeferredValue
Apply to our previous problem :
const AppWithAsynchronousRendering = () => {
const [counter, setCounter] = useState(0);
const deferredCounter = useDeferredValue(counter);
return (
<div className="App" style={AppStyle}>
<ExpensiveRenderComponent counter={deferredCounter} />
<BasicComponent counter={counter} />
<button onClick={() => setCounter(counter + 1)}>Increment</button>
</div>
);
}
ad locum ,useDeferredValue
Created counter
Delayed version of , It allows decoupling <ExpensiveRenderComponent/>
and <BasicComponent/>
Rendering of :
<BasicComponent/>
You can use the new immediatelycounter
.- meanwhile ,
deferredCounter
Keep the oldcounter
value , until React Finish using the newcounter
Value completes without blocking the main thread<ExpensiveRenderComponent/>
The calculation of . After completion ,<ExpensiveRenderComponent/>
It will be updated immediately , And the application is completely up-to-date .
Let's take a look at this hook The role of :
Because applications respond faster , The user experience has been greatly improved ! however , You'll notice UI Consistency has been sacrificed , because <ExpensiveRenderComponent/>
The old... Will be displayed in a short time counter
value . The solution to this problem is in UI It's not the latest time to notify users . It can be like introducing prop isStale
It's as simple as :
const AppWithAsynchronousRendering = () => {
const [counter, setCounter] = useState(0);
const deferredCounter = useDeferredValue(counter);
return (
<div className="App" style={AppStyle}>
<ExpensiveRenderComponent
counter={deferredCounter}
{/* You can return a loading state based on this prop */}
isStale={deferredCounter !== counter}
/>
<BasicComponent counter={counter} />
<button onClick={() => setCounter(counter + 1)}>Increment</button>
</div>
);
}
Now? , By means of isStale
by true Return to the loading state when UI It's easy to be consistent :
summary
- Have consistent React Mental models are not only the key to understanding and applying weird behaviors , It is also the key to effectively enhance it .
- React Rendering is synchronized and forced UI Uniformity . If some components need time to render ,UI It could become unresponsive .
- React 18 The concurrency feature supports asynchronous rendering .
useDeferredValue
You can delay the rendering of expensive components , And make UI More responsive . But if not handled properly , May sacrifice UI Uniformity . - React 18 There are many other concurrent rendering functions in :
useTransition
、Suspense
etc. .
Reference resources
边栏推荐
- Yyds dry goods inventory accelerating vacuum in PG
- Set status bar color
- Remote connection to MySQL under windows and Linux system
- How does proxy IP participate in the direct battle between web crawlers and anti crawlers
- Query word weight, search word weight calculation
- The basic steps of using information theory to deal with scientific problems are
- [staff] pitch representation (treble clef | C3 60 ~ B3 71 pitch representation | C4 72 pitch representation | C5 84 pitch representation)
- [untitled]
- 大厂裁员潮不断,双非本科出身的我却逆风翻盘挺进阿里
- Special symbols in SAP ui5 data binding syntax, and detailed explanation of absolute binding and relative binding concepts
猜你喜欢
Leetcode face T10 (1-9) array, ByteDance interview sharing
STM32__ 05 - PWM controlled DC motor
JVM面试篇
No programming code technology! Four step easy flower store applet
Sword finger offer 62 The last remaining number in the circle
Feature query of hypergraph iserver rest Service
【带你学c带你飞】1day 第2章 (练习2.2 求华氏温度 100°F 对应的摄氏温度
After marriage
How to turn off the LED light of Rog motherboard
Leetcode question brushing (10) - sequential question brushing 46 to 50
随机推荐
[staff] restore mark (Introduction to the use of restore mark | example analysis of Metaphone mark and restore mark)
how to come in an investnent bank team
Webgpu (I): basic concepts
AcWing 245. Can you answer these questions (line segment tree)
Software development life cycle -- waterfall model
What is the principle of bone conduction earphones and who is suitable for bone conduction earphones
MySQL operates the database through the CMD command line, and the image cannot be found during the real machine debugging of fluent
What are the characteristics of common web proxy IP
LeetCode刷题(十)——顺序刷题46至50
No programming code technology! Four step easy flower store applet
What is the function of the headphone driver
QT使用sqllite
SQL server calculates the daily average and annual average of the whole province
MVVM and MVC
Yyds dry goods inventory accelerating vacuum in PG
Types of exhibition items available in the multimedia interactive exhibition hall
QT实现界面跳转
Oracle creates a user with read-only permission in four simple steps
Flutter un élément au milieu, l'élément le plus à droite
Which brand of sports headset is better? Bluetooth headset suitable for sports