import {useEffect, useState} from "react"; import {useHistory} from "react-router-dom"; export const useSearchParam = (key, defaultValue = null) => { // Get a window.location.search param. const startingValue = new URLSearchParams(window.location.search).get(key); const [value, setValue] = useState(startingValue || defaultValue); const history = useHistory(); useEffect(() => { const params = new URLSearchParams(window.location.search); params.delete(key); if (value) { params.append(key, value); } history.push({search: params.toString()}); }, [value]) return [value, setValue]; }