Next.js Discord

Discord Forum

How does next.js subscribe to history state?

Answered
Horned oak gall posted this in #help-forum
Open in Discord
Horned oak gallOP
Hey folks, I was working to remove eslint warnings about router not being included in the dependencies array (using Page router, which gets an updated object reference every render). My first naive thought was to just manually create a hook that subscribes to history pop state and use history.pushstate to avoid the dependency altogether.

But. When trying to implement, discovered that browsers don't publish popState for every push or replace call, but only for specific user interactions. This made me suspect using history.pushState directly would prevent next router from seeing the updates. However, experimenting with it seems to show the opposite behavior. When I use window.history, next router picks up the changes just fine! It's magic! 🪄

I'm guessing there is a shim for window.history.pushState and replaceState (which is cool!), but I can't figure out where that shim lives. Anybody have a reference (e.g. in the router code) for "here is how the magic works"?
Answered by Horned oak gall
Whoops. I think I'm just wrong and my app state was being updated with things outside the next router. 😅
View full answer

1 Reply

Horned oak gallOP
Whoops. I think I'm just wrong and my app state was being updated with things outside the next router. 😅
Answer