M
M
miliko mikoyan2019-07-15 01:49:43
React
miliko mikoyan, 2019-07-15 01:49:43

Use case for useLayoutEffect + useState vs useMemo?

I saw this answer: useMemo vs. useEffect + useState and it fails useEffect well, but in my case I want to perform an expensive operation that changes the DOM as early as possible. Would useMemo() still be recommended instead of useLayoutEffect() for state updates? Does double effect rendering -> state update reflect any performance gain?
useLayoutEffect() script:

useLayoutEffect(() => {
    const tokens = expensiveOperationGeneratingClasses(param1)
    setTokens(tokens)
}, 
[param1])

 render (
  <>
   {
       tokens.map(token => <span className={token.id}/>)
   }
  </>
 )

useMemo script:
const tokens = useMemo(() => {
     return expensiveOperationGeneratingClasses(param1)
},
[param1]

 render (
  <>
   {
       tokens.map(token => <span className={token.id}/>)
   }
  </>
 )

Actually I realized that I'm not doing DOM operations but just generating class names before rendering tags to avoid flickering, so I think I'm better off using useMemo, am I right?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question