Skip to content

Instantly share code, notes, and snippets.

@mmyoji
Last active July 6, 2021 10:17
Show Gist options
  • Save mmyoji/53959ee0dfca649891743369d34178c0 to your computer and use it in GitHub Desktop.
Save mmyoji/53959ee0dfca649891743369d34178c0 to your computer and use it in GitHub Desktop.
8 Awesome React Hooks in TypeScript
// 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