Last active
December 23, 2020 07:19
-
-
Save hungdoansy/94524ee16bd723cd00b44061c74f26dc to your computer and use it in GitHub Desktop.
Simple & minimal useQueryParam hook
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 { 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