uft
    Preparing search index...

    Function lazy

    • Lazy initialization of a value.

      The given function is only called once and the result is cached, which is returned on subsequent calls.

      The given function is called the first time the returned function executes, storing its result. On subsequent calls, the cached value is returned unless the optional shouldReinitialize callback returns true, in which case the cached value is discarded and reinitialized.

      Type Parameters

      • T

      Parameters

      • fn: () => T

        A function initializing the value.

      • Optionaloptions: LazyOptions<T>

        Optional behavior overrides.

      Returns () => T

      A function returning the initialized value.

      It is safe for the given function to return undefined, this will not cause it to be called again.

      const value = lazy(() => {
      console.log('initializing')
      return 1
      })

      value() // 1, logs 'initializing'
      value() // 1, no log
      value() // 1, no log
      // On the client, the query client will only be created once.
      // On the server, every call to `getQueryClient` will create a new query client.
      const isBrowser = () => typeof window !== 'undefined'
      const getQueryClient = lazy(
      () => createQueryClient(),
      { shouldCache: isBrowser }
      )
      const getCounter = lazy(
      () => new Counter(),
      { shouldReinitialize: (counter) => counter.count >= 3 }
      )
      getCounter().inc() // 1
      getCounter().inc() // 2
      getCounter().inc() // 3
      // The count is 3, so this call to `getCounter()` will reinitialize the counter.
      getCounter().inc() // 1