Developpement web
ReactJS
Guides techniques

Ce hook de React sauvegarde un paramètre URL sans recharger la page !

Virgile Rietsch
Par Virgile RIETSCH·Fondateur Algomax · Ex-CTO
1 minutes de lecture102 vues
PartagerXLinkedInWhatsApp
Les 10 meilleurs hooks avec React Router 7

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
1
function useUpdateQueryStringValueWithoutNavigation(
2
queryKey: string,
3
queryValue: string,
4
) {
5
React.useEffect(() => {
6
const currentSearchParams = new URLSearchParams(window.location.search)
7
const oldQuery = currentSearchParams.get(queryKey) ?? ''
8
if (queryValue === oldQuery) return
9
10
if (queryValue) {
11
currentSearchParams.set(queryKey, queryValue)
12
} else {
13
currentSearchParams.delete(queryKey)
14
}
15
const 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-dom
20
// 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 trigger
22
// the loader to run which we do not want because all our data is already
23
// on the client and we're just doing client-side filtering of data we
24
// already have. So we manually call `window.history.pushState` to avoid
25
// the router from triggering the loader.
26
window.history.replaceState(null, '', newUrl)
27
}, [queryKey, queryValue])
28
}

Pages utiles pour approfondir

Si ce sujet vous concerne, ces pages vous aideront à comparer les options, cadrer un budget et choisir la bonne direction produit.

Vous voulez un SaaS ?

Plateforme SaaS sur mesure. Réservez un appel découverte gratuit.

Reste informé

Abonne-toi à notre newsletter pour recevoir les dernières mises à jour et insights.