haizlin / fe-interview

前端面试每日 3+1,以面试题来驱动学习,提倡每日学习与思考,每天进步一点!每天早上5点纯手工发布面试题(死磕自己,愉悦大家),6000+道前端面试题全面覆盖,HTML/CSS/JavaScript/Vue/React/Nodejs/TypeScript/ECMAScritpt/Webpack/Jquery/小程序/软技能……
http://www.h-camel.com
MIT License
25.27k stars 3.25k forks source link

[react] 请说说什么是useRef? #706

Open wwwind213 opened 5 years ago

wwwind213 commented 5 years ago

[react] 请说说什么是useRef?

zhaofeipeter commented 4 years ago

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

postbird commented 4 years ago

本质上 createRef 和 useRef(mountRef) 就是创建一个 {current: initialState} 对象然后返回

useRef 本身经历两个阶段:mountRef 和 updateRef,updateRef 就是把 memoziedState(上面创建的对象)返回。

在 reconciler 阶段,如果有 ref 绑定,会打一个 efftag:Ref

// 位操作标明有 ref 的变更标志位
function markRef(workInProgress: Fiber) {
  workInProgress.effectTag |= Ref;
}

在 commit 阶段,会通过判断是否存在 Ref 的副作用进行对应的处理,class component 返回类实例,而 DOM 则返回 DOM

wind8866 commented 3 years ago

他返回一个 {current: val } 对象,一般是用来获取真实DOM结构的,也能存储一些始终不应该改变的值。比如说 setTimeout 返回的定时器。可以存储在这里面,在其他事件回调中清除。