【发布时间】:2019-12-11 07:33:59
【问题描述】:
我正在用 React Hooks 编写我的产品,是的,我刚接触它。
今天我对 useCallback 性能进行了数学计算。这让我考虑了很多使用 useCallback 或不使用。
让我们看看。众所周知,useCallback 用于提高性能。
function MainScreen() {
const [email, setEmail] = useState("");
const [pwd, setPwd] = useState(""):
const onAuthenticate = useCallback(() => {
MyApi.authenticate(email, pwd);
}, [email, pwd]);
return <div>
<MyCustomButton onPress={onAuthenticate}>LOGIN</MyCustomButton>
</div>;
}
在上面的示例中,假设有两个输入电子邮件和密码,那么MyCustomButton 将在电子邮件或密码更改时呈现。我尝试使用useCallback 来减少渲染次数,但对我来说还不够好。
后来想了个办法,把依赖中的email和pwd取出来,用useRef保存email和密码的值。
function MainScreen() {
const [email, setEmail] = useState("");
const [pwd, setPwd] = useState(""):
const emailRef = useRef(email);
const pwdRef = useRef(pwd);
const onAuthenticate = useCallback(() => {
MyApi.authenticate(emailRef.current, pwdRef.current);
}, []);
useEffect(() => {
emailRef.current = email;
pwdRef.current = pwd;
}, [email, pwd]);
return <div>
<MyCustomButton onPress={onAuthenticate}>LOGIN</MyCustomButton>
</div>;
}
使用这种方法,它会在每次电子邮件或密码更改时停止在MyCustomButton 中呈现。
它实际上在性能和成本方面更好吗?小伙伴们怎么看?
感谢分享。
【问题讨论】:
标签: reactjs react-hooks