The problem

A function is very expensive computationally but other parts of the UI need to be refreshed quickly.

 

The solution - reduce running the expensive computation every frame. Only update when there is enough time.

 

Introduction to useDeferredValue

This is similar to deBounce, but is more tied in with how React renders.

You can tell React that some part of the code is at a lower priority. 

 

deferredInput is only updated once input has not changed for a while (like deBounce).

The change then triggers the code in useMemo to be recalculated.

 

function List( {input } ) {

  const LIST_SIZE = 20000

  const deferredInput = useDeferredValue(input)

  const list = useMemo(() => {

       const l = []

      for ( let i=0; i< LIST_SIZE;i++) {

         l.push(<div key={i}>{deferredInput}</div>)

     }

     return l

    }, [deferredInput])


    useEffect(() => {
       console.log(`Input ${input}\nDeferred: ${deferredInput}`)

    }, [input, deferredInput])



  return list

}