by karaokeyoga · 3y ago · 0 comments
- the function is run immediately (during the render cycle, not after)
- we can take advantage of the dependency array
I think the reason this pattern isn't more popular is that we're taught to use useMemo to memoize a result, but we can also use it more simply … to run a function (during the render cycle) whenever the dependency array changes.
Just call useMemo and don't assign the result to anything, such as:
useMemo(myFunction, [dependency array])
Many applications suffer from the waterfall rendering problem but even for those that don't, if they are large, they will absolutely want to kick off network calls on "the way down". You can easily add a ton of time to LCP by waiting to kick network calls off until the tree has mounted.
I actually go a little out of my way to make sure as much of the tree as possible can render and mount with missing data. This way the work is occurring while data is fetching in parallel, and then a minimized number of components need to be updated once the data has arrived.
You can confirm this via console.log:
useMemo(() => console.log(1), [])
console.log(2)
… will print 1 then 2.
If you replace useMemo with useLayoutEffect, you’ll get 2 then 1.