Skip to content

Instantly share code, notes, and snippets.

View sophister's full-sized avatar

Jesse sophister

  • Beijing, China
View GitHub Profile
@sophister
sophister / useDebounce.ts
Last active August 25, 2020 10:39
React Hooks for debounce, useDebounce, useDebounceState, with cleanup surpport
import { useState, useEffect, useRef, useCallback } from "react";
export function useDebounceState<T>(initValue: T, delay: number) {
const [value, setValue] = useState<T>(initValue);
const timerRef = useRef(null);
// reset timer when delay changes
useEffect(
function () {
if (timerRef.current) {
clearTimeout(timerRef.current);