Retour aux articles
Ce hook de React sauvegarde un paramètre URL sans recharger la page !
1 minutes de lecture97 vues

J'ai découvert ce hook il y a quelques jours sur le Discord de Remix. Encore mieux que le hook useSearchParams(), qui permet de modifier les paramètres dans l'URL. Il effectue également un rechargement des données côté serveur (et donc, de la page).
useUpdateQueryStringValueWithoutNavigation
Je souhaitais éviter de recharger la page à chaque fois, et j'ai découvert useUpdateQueryStringWithoutNavigation.
Lien vers le hook : https://github.com/kentcdodds/kentcdodds.com/blob/main/app/utils/misc.tsx#L299
useUpdateQueryStringValueWithoutNavigation.tsx
1function useUpdateQueryStringValueWithoutNavigation(2queryKey: string,3queryValue: string,4) {5React.useEffect(() => {6const currentSearchParams = new URLSearchParams(window.location.search)7const oldQuery = currentSearchParams.get(queryKey) ?? ''8if (queryValue === oldQuery) return910if (queryValue) {11currentSearchParams.set(queryKey, queryValue)12} else {13currentSearchParams.delete(queryKey)14}15const newUrl = [window.location.pathname, currentSearchParams.toString()]16.filter(Boolean)17.join('?')18// alright, let's talk about this...19// Normally with remix, you'd update the params via useSearchParams from react-router-dom20// and updating the search params will trigger the search to update for you.21// However, it also triggers a navigation to the new url, which will trigger22// the loader to run which we do not want because all our data is already23// on the client and we're just doing client-side filtering of data we24// already have. So we manually call `window.history.pushState` to avoid25// the router from triggering the loader.26window.history.replaceState(null, '', newUrl)27}, [queryKey, queryValue])28}