Support reading history.state #63708
GriffinSauce
started this conversation in
Ideas
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Goals
history.state
from the router from a hook in a way that triggers a (client) re-renderreact-router
for existing projects that rely on this featureNon-Goals
history.state
is not supported in SSR, this can be an acceptable trade-off for what it provides for client-side interactions and easing migration.Background
Why
The App router supports the native
history.pushState
andhistory.replaceState
which allow setting a state value per history entry. At the moment there is no way to read this state and re-render when the user navigates back/forward in the stack.We use this feature extensively with
react-router
for modals which we want in the history stack but not to have their own URL, for example a full screen date-picker overlay on mobile. For the user this appears like a temporary view which may be closed/reopened with native browser back actions. This matches their expectations better than leaving the entire page when they hit a native "back" button.Some of these interactions may be replaced by parallel / intercepting routes but this does not make sense for all features.
This is a blocker for us to migrate some of our main projects to Next from
react-router
/CRA
after a happy migration of more minor apps.Caveats / why not
As mentioned above: this state will not be available on the server. So SRR will always render the page without this state and potentially causes more client-side renders. That said, this something the user can mitigate by only using the hook in a client component which stays mounted. This means there is only an additional client-side render in the case of a full page refresh (after setting any history state).
This is a trade-off that can be documented and considered, with a strong suggestion to prefer using parallel / intercepting routes where it makes sense.
Alternatives
/login
, but not features which are more contextual or ephemeral (date picker, content detail views)history
package (whichreact-router
relies on) on top of the Next App router to interact with and read the history state - this is a workaround we are exploring but mixing the two seems unwise for the long term.Proposal
Rough proposal:
popState
event is triggered (by forward / back navigation)pushState
/replaceState
is called (these are already monkey-patched to keep the URL in sync)useHistoryState
hook oruseRouter().state
useHistoryState
could throw an error in server components to prevent SSR issuesI'd be happy to contribute changes if we can agree on the goals and design.
Either way thanks for the consideration 🙏
Beta Was this translation helpful? Give feedback.
All reactions