forked from Joystream/atlas
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix weird loading animation for carousels
- Loading branch information
Showing
3 changed files
with
20 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,15 +1,24 @@ | ||
import { useEffect, useState } from 'react' | ||
|
||
export function useDebounceValue<T>(value: T, delay?: number): T { | ||
const [debouncedValue, setDebouncedValue] = useState<T>(value) | ||
export function useDebounceValue<T, R extends boolean = false>( | ||
value: T, | ||
delay?: number, | ||
emptyInitialValue?: R | ||
): R extends true ? T | null : T { | ||
type ReturnType = R extends true ? T | null : T | ||
// Initialize the state with appropriate type | ||
const [debouncedValue, setDebouncedValue] = useState<R extends true ? T | null : T>( | ||
emptyInitialValue ? (null as ReturnType) : (value as ReturnType) | ||
) | ||
|
||
useEffect(() => { | ||
const timer = setTimeout(() => setDebouncedValue(value), delay ?? 500) | ||
const timer = setTimeout(() => setDebouncedValue(value as ReturnType), delay ?? 500) | ||
|
||
return () => { | ||
clearTimeout(timer) | ||
} | ||
}, [value, delay]) | ||
|
||
// TypeScript will infer the return type based on the value of emptyInitialValue | ||
return debouncedValue | ||
} |