Skip to content

Instantly share code, notes, and snippets.

@jacksteamdev
Last active January 30, 2020 20:39
Show Gist options
  • Save jacksteamdev/df36886d786803ee724a4d41dbda0d66 to your computer and use it in GitHub Desktop.
Save jacksteamdev/df36886d786803ee724a4d41dbda0d66 to your computer and use it in GitHub Desktop.
React Hooks in TypeScript
import { useEffect, useState } from 'react'
export function useDebounce<T>(value: T, delay: number) {
// State and setters for debounced value
const [debouncedValue, setDebouncedValue] = useState<T | undefined>()
useEffect(
() => {
// Update debounced value after delay
const handler = setTimeout(() => {
setDebouncedValue(value)
}, delay)
// Cancel the timeout if value changes (also on delay change or unmount)
// This is how we prevent debounced value from updating if value is changed ...
// .. within the delay period. Timeout gets cleared and restarted.
return () => {
clearTimeout(handler)
}
},
[value, delay], // Only re-call effect if value or delay changes
)
return debouncedValue
}
import { useState, useEffect } from 'react'
import { Observable } from 'rxjs'
export const useObservable = <T extends any>(
observable: Observable<T>,
initializer: T,
) => {
const state = useState(initializer)
useEffect(() => {
const subscription = observable.subscribe(state[1])
return () => {
subscription.unsubscribe()
}
}, [state[0]])
return state[0]
}
import { useState } from 'react'
export const useSwitch = <T extends string>(...states: T[]) => {
const [index, setIndex] = useState(0)
return [
states[index],
() => {
setIndex(index === states.length - 1 ? 0 : index + 1)
},
] as const
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment