Last active
January 30, 2020 20:39
-
-
Save jacksteamdev/df36886d786803ee724a4d41dbda0d66 to your computer and use it in GitHub Desktop.
React Hooks in TypeScript
This file contains hidden or 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
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 | |
} |
This file contains hidden or 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
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] | |
} |
This file contains hidden or 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
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