Skip to content

Instantly share code, notes, and snippets.

@guillermodlpa
Created January 12, 2023 07:37
Show Gist options
  • Save guillermodlpa/1148b2a0409c2730f65abc49c25a49fb to your computer and use it in GitHub Desktop.
Save guillermodlpa/1148b2a0409c2730f65abc49c25a49fb to your computer and use it in GitHub Desktop.
React hook guideline implementation to update the URL with a debounce in Next.js
function getBrowserPath(params) {
// your implementation here
}
const URL_UPDATE_DELAY = 750;
export default function useKeepBrowserPathUpdated(params) {
const path = getBrowserPath(params);
useEffect(() => {
// the timeout adds a small delay to reduce the errors logged
// by Next when a navigation is interrupted
const timeout = setTimeout(() => {
Router.replace(
path,
undefined,
{ shallow: true } // optimistic shallow true
);
}, URL_UPDATE_DELAY);
return function cleanUp() {
clearTimeout(timeout);
};
}, [path]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment