# All files / utils useLazyMemo.ts

38.89% Statements 7/18
16.67% Branches 1/6
50% Functions 1/2
41.18% Lines 7/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    381x

    1x

    4x
    4x
    4x

    4x
    4x

     import {useRef, DependencyList} from 'react'

    /*
      A hook that works like `useMemo`, but takes an additional boolean argument.
      The factory will not be called until the boolean is true; until then, `null`
      is returned.
    */
    export const useLazyMemo = <T>(
      factory: () => T,
      deps: DependencyList,
      canCompute: boolean
    ): T | null => {
      const hasComputed = useRef(false)
      const result = useRef<T>(null)
      const prevDeps = useRef(deps)

      Eif (!canCompute) {
        return null
      }

      if (!hasComputed.current) {
        hasComputed.current = true
        result.current = factory()
        prevDeps.current = deps

        return result.current
      }

      const depsChanged = deps.some((x, i) => x !== prevDeps.current[i])

      if (depsChanged) {
        result.current = factory()
        prevDeps.current = deps
      }

      return result.current
    }