Created
January 12, 2023 07:37
-
-
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
This file contains hidden or 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
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