Initialize const value with useCallback

Recently I looked into some code that initialize a const with a function, some like this:

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:

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.

Any advice will be highly appreciated.


You are looking for useMemo

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