Skip to content

Instantly share code, notes, and snippets.

@davemecha
Last active October 9, 2023 07:03
Show Gist options
  • Save davemecha/4d9e1eee2ac23138e9a84b0a609a4be6 to your computer and use it in GitHub Desktop.
Save davemecha/4d9e1eee2ac23138e9a84b0a609a4be6 to your computer and use it in GitHub Desktop.
Typed debounced selector for react-redux
import { useEffect, useRef, useState } from 'react';
import { TypedUseSelectorHook, useSelector } from 'react-redux';
// S is the RootState. If used with reselect, it can be derived. Otherwise, it could also initialized here with S = RootState
export function useDebouncedSelector<T, S>(selector: (state: S) => T, time = 100, equalityFn?: (left: T, right: T) => boolean) {
const useAppSelector: TypedUseSelectorHook<S> = useSelector;
const [state, setState] = useState<{ data: T | undefined }>({ data: undefined });
const result = useRef<T>();
const data = useAppSelector<T>(selector, equalityFn);
useEffect(() => {
const handler = setTimeout(() => {
if (result.current !== data) {
result.current = data;
setState({ data });
}
}, time);
return () => clearTimeout(handler);
}, [data, time]);
return state.data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment