不理解官方的一个faqlink
If the function you’re memoizing is an event handler and isn’t used during rendering
上边这句话是官方的原话, 但我觉得没什么道理...
在我看来下面两种写法没有任何区别, 请指点;
import React, { useState, useCallback, useEffect, useRef } from 'react';
function Form() {
const [text, updateText] = useState('');
const textRef = useRef();
useEffect(() => {
textRef.current = text; // Write it to the ref
});
const handleSubmit = useCallback(() => {
const currentText = textRef.current; // Read it from the ref
console.log(currentText);
}, [textRef]); // Don't recreate handleSubmit like [text] would do
// const handleSubmit = useCallback(() => {
// console.log(text);
// }, [text]);
return (
<>
<input value={text} onChange={e => updateText(e.target.value)} />
<button onClick={handleSubmit}>click</button>
</>
);
}
export default Form;
useCallback的依赖是只比较值的, 如果是对象, 就是只比较引用
而textRef是一直存在不会销毁的跨生命周期对象, 引用一直不变, so, 相当于, useCallback的依赖为[]
ps: 为什么只比较引用呢, 我觉得, 因为useCallback/useEffect的依赖里基本都该是useState的返回值, 而每次调用setState都会赋给state一个全新的值, 如果是对象, 引用就变了, so, 只需要比较值(对象的话是地址)就知道依赖有没有变化