about summary refs log tree commit diff
path: root/src/components/hooks/useDelayedLoading.ts
blob: 6c7e2ede06eb79a5c5ca0d49c9f93bf76b315516 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import React from 'react'

export function useDelayedLoading(delay: number, initialState: boolean = true) {
  const [isLoading, setIsLoading] = React.useState(initialState)

  React.useEffect(() => {
    let timeout: NodeJS.Timeout
    // on initial load, show a loading spinner for a hot sec to prevent flash
    if (isLoading) timeout = setTimeout(() => setIsLoading(false), delay)

    return () => timeout && clearTimeout(timeout)
  }, [isLoading, delay])

  return isLoading
}