Last active
October 9, 2023 07:03
-
-
Save davemecha/4d9e1eee2ac23138e9a84b0a609a4be6 to your computer and use it in GitHub Desktop.
Typed debounced selector for react-redux
This file contains 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, 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