简体   繁体   English

使用 useCallback 初始化 const 值

[英]Initialize const value with useCallback

Recently I looked into some code that initialize a const with a function, some like this:最近我研究了一些用 function 初始化 const 的代码,有些像这样:

const myConst = myFn();

The "problem" is this function will be call in every render, and in the component happens a lot,to prevent this I can change the const to a state and work with useEffect, but now I'm wondering if I can make use of the useCallback hook, something like this: “问题”是这个 function 将在每次渲染中调用,并且在组件中发生了很多,为了防止这种情况我可以将 const 更改为 state 并使用 useEffect,但现在我想知道我是否可以使用useCallback 钩子,如下所示:

const [myState] = useState(useCallback(() => myFn(), []))

Logging myFn() is just called once, but I'm not really sure if it's ok to do this, or if this is really helping to improve the performance.记录 myFn() 只调用一次,但我不确定这样做是否可以,或者这是否真的有助于提高性能。

Any advice will be highly appreciated.任何建议将不胜感激。

You are looking for useMemo您正在寻找useMemo

const value = useMemo(() => { 
                         ..some computation 
                         return result; 
                       }, []);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM