beautiful-react-hooks
Version:
A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development
35 lines (34 loc) • 1.16 kB
JavaScript
import { useCallback, useRef } from 'react';
import { useHistory } from 'react-router-dom';
import useDidMount from './useDidMount';
import useURLSearchParams from './useURLSearchParams';
/**
* Ease the process of modify the query string in the URL for the current location.
*/
const useQueryParam = (key, options = {}) => {
const history = useHistory();
const params = useURLSearchParams();
const initialisedRef = useRef(false);
const onMount = useDidMount();
const setParam = useCallback((nextValue) => {
if (!nextValue) {
params.delete(key);
}
else {
params.set(key, nextValue);
}
if (options.replaceState) {
history.replace({ search: params.toString() });
return;
}
history.push({ search: params.toString() });
}, [options.replaceState, history]);
onMount(() => {
if (!params.has(key)) {
initialisedRef.current = true;
setParam(options.initialValue);
}
});
return [initialisedRef.current ? params.get(key) : options.initialValue, setParam];
};
export default useQueryParam;