Skip to content

Commit 6f9048e

Browse files
author
devgioele
committed
add utils useDebounce and useIsMounted
1 parent 6d22af1 commit 6f9048e

3 files changed

Lines changed: 41 additions & 20 deletions

File tree

src/index.ts

Lines changed: 7 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,7 @@
1-
import { useInterval } from './useInterval/useInterval'
2-
import { AsyncState, getAsyncState } from './async-data/asyncState'
3-
import { AsyncView } from './async-data/AsyncView'
4-
import {
5-
LocationProvider,
6-
LocationContext,
7-
LocationContextValue,
8-
} from './location-provider/LocationProvider'
9-
import { useMatchMediaQuery } from './useMatchMediaQuery/useMatchMediaQuery'
10-
11-
export {
12-
useInterval,
13-
AsyncState,
14-
getAsyncState,
15-
AsyncView,
16-
LocationProvider,
17-
LocationContext,
18-
LocationContextValue,
19-
useMatchMediaQuery,
20-
}
1+
export * from './useInterval/useInterval'
2+
export * from './async-data/asyncState'
3+
export * from './async-data/AsyncView'
4+
export * from './location-provider/LocationProvider'
5+
export * from './useMatchMediaQuery/useMatchMediaQuery'
6+
export * from './useDebounce/useDebounce'
7+
export * from './useIsMounted/useIsMounted'

src/useDebounce/useDebounce.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { useEffect, useState } from 'react'
2+
3+
export function useDebounce<T>(data: T, interval: number): T {
4+
const [liveData, setLiveData] = useState<T>(data)
5+
6+
useEffect(() => {
7+
if (typeof window !== 'undefined') {
8+
const handler = window.setTimeout(() => {
9+
setLiveData(data)
10+
}, interval)
11+
return () => {
12+
window.clearTimeout(handler)
13+
}
14+
}
15+
return undefined
16+
}, [data, interval])
17+
18+
return liveData
19+
}

src/useIsMounted/useIsMounted.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { useCallback, useEffect, useRef } from 'react'
2+
3+
export function useIsMounted() {
4+
const isMounted = useRef(false)
5+
6+
useEffect(() => {
7+
isMounted.current = true
8+
9+
return () => {
10+
isMounted.current = false
11+
}
12+
}, [])
13+
14+
return useCallback(() => isMounted.current, [])
15+
}

0 commit comments

Comments
 (0)