Skip to content

Instantly share code, notes, and snippets.

@hungdoansy
Last active December 23, 2020 07:19
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 hungdoansy/94524ee16bd723cd00b44061c74f26dc to your computer and use it in GitHub Desktop.
Save hungdoansy/94524ee16bd723cd00b44061c74f26dc to your computer and use it in GitHub Desktop.
Simple & minimal useQueryParam hook
import { useCallback } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import queryString from 'query-string';
const useQueryParam = (key) => {
const history = useHistory();
const location = useLocation();
const { search } = location;
const params = queryString.parse(search);
const updateHistoryQueryString = useCallback((params) => {
const newQueryString = queryString.stringify(params);
const newLocation = `${location.pathname}${newQueryString && '?'}${newQueryString}`;
history.push(newLocation);
}, [history, location.pathname]);
const updateParam = useCallback((value) => {
updateHistoryQueryString({ ...params, [key]: value });
}, [key, params, updateHistoryQueryString]);
const removeParam = useCallback(() => {
updateHistoryQueryString({ ...params, [key]: undefined });
}, [key, params, updateHistoryQueryString]);
return { value: params[key], updateParam, removeParam };
};
export default useQueryParam;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment