当前位置:网站首页>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
边栏推荐
- The wave of layoffs in big factories continues, but I, who was born in both non undergraduate schools, turned against the wind and entered Alibaba
- 【OpenCV】-5种图像滤波的综合示例
- Flutter un élément au milieu, l'élément le plus à droite
- 结婚后
- Software testing learning notes - network knowledge
- Share the basic knowledge of a common Hongmeng application
- Divorce for 3 years to discover the undivided joint property, or
- 多线程查询,效率翻倍
- [road of system analyst] collection of wrong topics in enterprise informatization chapter
- Vsocde has cli every time it is opened js
猜你喜欢
Jvm-01 (phased learning)
[staff] pitch representation (treble clef | C3 60 ~ B3 71 pitch representation | C4 72 pitch representation | C5 84 pitch representation)
【读书笔记】程序员修炼手册—实战式学习最有效(项目驱动)
Multi threaded query, double efficiency
Après le mariage
A quick understanding of analog electricity
QT实现界面跳转
What kind of good and cost-effective Bluetooth sports headset to buy
Additional: information desensitization;
How to hide the scroll bar of scroll view in uniapp
随机推荐
大厂裁员潮不断,双非本科出身的我却逆风翻盘挺进阿里
[staff] restore mark (Introduction to the use of restore mark | example analysis of Metaphone mark and restore mark)
SQL server calculates the daily average and annual average of the whole province
[punch in questions] integrated daily 5-question sharing (phase II)
SAP ui5 beginner tutorial 19 - SAP ui5 data types and complex data binding
Connected block template and variants (4 questions in total)
Which brand of running headphones is good? How many professional running headphones are recommended
flutter 中间一个元素,最右边一个元素
Kibana controls es
Coordinatorlayout + tablayout + viewpager2 (there is another recyclerview nested inside), and the sliding conflict of recyclerview is solved
Pat a-1165 block reversing (25 points)
多线程查询,效率翻倍
Set status bar color
Batch detect whether there is CDN in URL - high accuracy
Kibana操控ES
2022 safety officer-c certificate examination questions and mock examination
After marriage
Cesium dynamic diffusion point effect
2022安全员-C证考试题及模拟考试
A quick understanding of digital electricity