type UseClickOutside = (
ref: React.RefObject<Node>,
fn: ClickOutsideFn,
opts?: Partial<ClickOutsideOpts>,
) => void
type ClickOutsideFn = (evt: Event) => void
type ClickOutsideOpts = {
root: React.RefObject<Node>
except: React.RefObject<Node>[]
listenerType: keyof DocumentEventMap
listenerOpts: boolean | AddEventListenerOptions
}
const ref = useRef<HTMLDivElement | null>(null)
useClickOutside(ref, fn)
type UseDebounce = <T extends Function>(
fn: T,
opts?: number | Partial<DebounceOpts>,
) => Debounce<T>
type DebounceOpts = {
delay: number
persist: boolean
}
type Debounce<T extends Function> = {
(...params: Parameters<T>): void
abort: () => void
terminate: () => void
}
const handler = useDebounce(() => console.log("Hello!"), 1000)
<button onClick={handler}>
Say hello with delay
</button>
<button onClick={handler.abort}>
Abort
</button>
<button onClick={handler.terminate}>
Terminate
</button>
type UseTimeout = <T extends Function>(
fn: T,
opts?: number | Partial<TimeoutOpts>,
) => Timeout<T>
type TimeoutOpts = {
delay: number
persist: boolean
}
type Timeout<T extends Function> = {
(...params: Parameters<T>): void
abort: () => void
terminate: () => void
}
const handler = useTimeout(() => console.log("Hello!"))
<button onClick={handler}>
Say hello with delay
</button>
<button onClick={handler.abort}>
Abort
</button>
<button onClick={handler.terminate}>
Terminate
</button>
type UseInterval = (
fn: IntervalFn,
opts?: number | Partial<IntervalOpts>,
) => ToggleState
type IntervalFn = () => void
type IntervalOpts = {
delay: number
autoStart: boolean
}
const [isOn, toggle] = useInterval(() => {
console.log("Hello with interval!")
})
type UseStoredState = <T>(
name: string,
opts?: T | Partial<StoredStateOpts<T>>,
) => [T, (val: T) => Promise<void>, boolean]
type StoredStateDriver = "LOCALSTORAGE" | "WEBSQL" | "INDEXEDDB"
type StoredStateOpts<T> = {
defaultVal: T
driver: StoredStateDriver
}
const [val, setVal, isReady] = useStoredState("key", "defaultValue")
return isReady ? val : null
type UseToggle = (defaultVal?: any) => ToggleState
type ToggleState = [boolean, (val?: any) => void]
const [isOn, toggle] = useToggle()
type UseSubject = <T>(
subject$: Subject<T>,
fn: SubjectFn<T>,
) => void
type SubjectFn<T> = (val: T) => void
useSubject(subject$, fn)
type UseBehaviorSubject = <T>(
subject$: BehaviorSubject<T>,
fn?: BehaviorSubjectFn<T>,
) => BehaviorSubjectState<T>
type BehaviorSubjectState<T> = [T, BehaviorSubjectFn<T>]
type BehaviorSubjectFn<T> = (val: T) => void
const [val, setVal] = useBehaviorSubject(subject$, fn)