当前位置:网站首页>Interviewer: the difference between uselayouteffect and useeffect
Interviewer: the difference between uselayouteffect and useeffect
2022-06-23 22:27:00 【Whole stack Xiaochen】
interviewer :useLayoutEffect and useEffect The difference between
hello, This is Xiaochen , Have you ever encountered such a problem during the interview ,useLayoutEffect and useEffect What's the difference , You may answer useEffect It's asynchronous ,useLayoutEffect It's synchronous , The interviewer will be really satisfied with this answer , We need to make it clear when they are called in the source code .
So let's do an example : After clicking trigger update , If count The previous state was 0, We randomly generate a number , After blocking for a period of time , Set up count Bit random value , Look at the useEffect and useLayoutEffect What's the difference between the two cases
import React, { useLayoutEffect, useState, useEffect } from "react";
export default function App() {
const [count, setCount] = useState(0);
// use useLayoutEffect try
useEffect(() => {
if (count === 0) {
const randomNum = Math.random() * 100;// I'm going to randomly generate a number
const now = performance.now();
while (performance.now() - now < 100) {// Block for a period of time
console.log('blocking...');
}
setCount(randomNum);// Reset the status , Set to random number
}
}, [count]);
return <div onClick={() => setCount(0)}>{count}</div>;
}
// stay useEffect Under the circumstances , Keep clicking to trigger updates , Occasionally 0
// stay useLayoutEffect Under the circumstances , Keep clicking to trigger updates , Not occasionally 0In the source code, no matter when rendering or updating for the first time, it will go through a stage called commit Stage , The main work in this stage is to deal with some hook functions 、 Life cycle 、 Traverse render It's formed in stages EffectList Linked list , Will have side effects Fiber Apply nodes to real nodes , If the render If you don't understand this stage, you can refer to previous articles render Stage , Here is the graph commit Structure diagram of phase source code , Let's explain in detail .
stay commitRootImpl The function of is mainly divided into three parts :
- commit Stage pre work
- mutation Stage
- call commitBeforeMutationEffects,scheduleCallback Scheduling execution flushPassiveEffects
- call commitMutationEffects, Dealing with related side effects , Operate on real nodes useLayoutEffect The destruction function of the is executed in this function
- call commitLayoutEffects, call commitLayoutEffects Callback function for , At this time, the side effects have been applied to the real nodes , So you can get the latest node .
- stay commit After the end of the phase flushPassiveEffects perform useEffect Destruction function and callback function .
- commit Phase closeout
therefore useLayout/componentDidMount and useEffect What's the difference ?
answer : They are commit Different stages, different timing ,useEffect stay commit End of phase asynchronous call ,useLayout/componentDidMount A synchronous invocation
Detailed source debugging video ( Efficient learning ): Click to learn
In the past react Source code analysis article :
1. Introduction and interview questions
4. Source directory structure and debugging
6.legacy and concurrent Pattern entry function
19. Handwritten mini version react
20. summary & The answers to the interview questions in Chapter one
边栏推荐
- How does the fortress remote login server operate? What is the application value of Fortress machine?
- WordPress plugin smart product review 1.0.4 - upload of any file
- Why is easycvr cascaded to the parent platform not displayed?
- Some opinions on microservices
- Service API version design and Practice
- Batch production of plant hangtag
- Ten thousand words! Understand the inheritedwidget local refresh mechanism
- The time deviation is more than 15 hours (54000 seconds), and the time cannot be automatically calibrated
- Take you to understand the lazy loading of pictures
- How to set secondary title in website construction what is the function of secondary title
猜你喜欢

Game security - call analysis - write code

Pourquoi une seule valeur apparaît - elle sur votre carte de données?

Opengauss Developer Day 2022 was officially launched to build an open source database root community with developers

Beauty of script │ VBS introduction interactive practice

脚本之美│VBS 入门交互实战

Hackinglab penetration test question 8:key can't find it again

Ten thousand words! Understand the inheritedwidget local refresh mechanism

Application practice | Apache Doris integrates iceberg + Flink CDC to build a real-time federated query and analysis architecture integrating lake and warehouse

为什么你的数据图谱分析图上只显示一个值?

為什麼你的數據圖譜分析圖上只顯示一個值?
随机推荐
What should I do if the RDP fortress server connection times out? Why should enterprises use fortress machines?
Achieve scoring (Star scoring) effect through native JS
What is the meaning of the two-way and one-way cn2 lines in Hong Kong, China?
2008R2 CFS with NFS protocol
Icml2022 | robust task representation for off-line meta reinforcement learning based on contrastive learning
Integrated management and control system of 3D intelligent warehousing and logistics park
Devops sharing: how to hold the meeting?
Implement sequence restriction on memory operations
How do fortress computers log in to the server? What is the role of the fortress machine?
[tcapulusdb knowledge base] example of deleting data (TDR table)
SLSA: 成功SBOM的促进剂
How to select Poe, poe+, and poe++ switches? One article will show you!
The article "essence" introduces you to VMware vSphere network, vswitch and port group!
Error message - Customizing incorrectly maintained – in transaction code ML81N
[tutorial] build a personal email system using Tencent lightweight cloud
How to deploy API gateways and split services under multi services?
CMU doctoral thesis | meta reinforcement learning through memory, 118 Pages pdf
How to set the protective strip in the barcode
Command line enumeration, obtaining and modifying time zones
What is the was fortress server restart was command? What are the reasons why was could not be restarted?