Skip to content

Instantly share code, notes, and snippets.

@sankargorthi
Last active September 21, 2020 01:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sankargorthi/dced9e4d8e4db905033357ef57d1b4f6 to your computer and use it in GitHub Desktop.
Save sankargorthi/dced9e4d8e4db905033357ef57d1b4f6 to your computer and use it in GitHub Desktop.
Debounced searchbox with persistent state
export const useSearchConfig = () => useContext(SearchContext);
export const useSetSearchConfig = () => useContext(SetSearchContext);
export function Application({ children, changingParam }) {
const [searchConfig, setSearchConfig] = usePersistentState(
`MyComponent${changingParam}`,
{ searchTerm: '', sortDirection: ASC },
)
return (
<SearchContext.Provider value={searchConfig}>
<SetSearchContext.Provider value={setSearchConfig}>
<SlowSearchbox />
<SearchDependent />
</SetSearchContext.Provider>
</SearchContext.Provider>
)
}
export function SlowSearchbox() {
const { searchTerm } = useSearchConfig()
const setSearchConfig = useSetSearchConfig()
return <Searchbox value={term} onChange={(e, v) => setSearchConfig(c => ({...c, searchTerm: v})} />
}
export default function SearchDependent() {
const { searchConfig: fast } = useSearchConfig();
// Debounce here instead of in the searchbox
const searchConfig = useDebounce(slow);
const filtered = filter(data, searchConfig);
return <MainContent list={filtered} />
}
export default function useDebounce(value, delay = 300 /* default delay */) {
const [debounced, setDebounced] = useState(value)
useEffect(() => {
const handler = setTimeout(() => setDebouncedValue(value), delay)
return () => clearTimeout(handler)
}, [value, delay])
return debounced
}
// returns `null` if no stored value exists
const readFromStorage = (key) => …
export default function usePersistentState(key, initialValue) {
const [value, setValue] = useState(() => readFromStorage(key) || initialValue)
useEffect(() => {
const saved = readFromStorage(key)
if (saved) setValue(saved)
}, [key])
useEffect(() => {
writeToStorage(key, value)
}, [key, value])
return [value, setValue]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment