Last active
July 6, 2021 10:17
-
-
Save mmyoji/53959ee0dfca649891743369d34178c0 to your computer and use it in GitHub Desktop.
8 Awesome 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
// Original Article: https://thesmartcoder.dev/awesome-react-hooks/ | |
// | |
// I just wrote hooks that I'm interested in. | |
import { useRef, useEffect, useState } from "react"; | |
function useTimeout(callback: Callback, delay: number) { | |
const savedCallback = useRef<Callback>(); | |
useEffect(() => { | |
savedCallback.current = callback; | |
}, [callback]); | |
useEffect(() => { | |
function tick() { | |
if (savedCallback.current) { | |
savedCallback.current(); | |
} | |
} | |
const id = setTimeout(tick, delay); | |
return () => clearTimeout(id); | |
}, [delay]); | |
} | |
function usePrevious<T>(value: T) { | |
const ref = useRef<T>(); | |
useEffect(() => { | |
ref.current = value; | |
}); | |
return ref.current; | |
} | |
// If you write `useFetch` by yourself, | |
// use `useSWR` or `useQuery`s in `@apollo/client`. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment