wouter Switch matches less-specific Route for 1 render when using browser 'back' button
Issue
- I am using Wouter/React/Vite.
- When using
<Switch>, it seems the incorrect route is matched for 1 frame when using the browser back button. - Even though the more specific route is listed first, the less specific route is matched for 1 frame.
- This causes problems in the less-specific route component if we depend on a route parameter:
- In my example (https://github.com/doggan/wouter-back-bug/blob/main/src/App.tsx#L16-L17), I have hooks that depend on the route parameter. This component expects the ids to be of some form
123456, but when using the browser back button, it will be called once with the idnew, even though the more specific route should have matched that route. - As workaround, I can add logic to not execute hook logic when id === new, but this is hacky and the hooks shouldn't need to know about other routes in the application. It's also complicated by the fact that we can't conditionally render hooks.
- In my example (https://github.com/doggan/wouter-back-bug/blob/main/src/App.tsx#L16-L17), I have hooks that depend on the route parameter. This component expects the ids to be of some form
Repro
Resources
- minimal repro example: https://github.com/doggan/wouter-back-bug/blob/main/src/App.tsx
- repo if needed: https://github.com/doggan/wouter-back-bug/tree/main
- deployed version to repro: https://wouter-back-bug.vercel.app/characters/new
Steps
- Go to
characters/newroute. The CharacterCreationPage component is correctly rendered. - Click link to navigate to
characters/123456route. The CharacterPage component is correctly rendered. - Click browser back button to go back to
characters/new.
- Actual: The CharacterPage component is rendered once with
newas it's parameter id, and then the CharacterCreationPage component is rendered. You can see from the console.logs: - Expected: The CharacterCreationPage should be rendered. The CharacterPage should not be rendered since the route doesn't match. You can see from the console.logs:
- Note: This "correct" behavior is achieved by clicking on a Link. The bug only happens when using the browser 'back' button.
Thank you for reading! I really appreciate the work put into this library. This has been the one small issue I've encountered so far.
Hi @doggan apologies for late reply! Just to confirm: the CharacterPage is rendered briefly and then immediatelly after that, the creation page is shown?
@molefrog Yep, exactly.
From the first screenshot, you can see the ### CharacterPage: true new log is rendered once when clicking "back".
But this log should not be called, because the route should redirect immediately to the CharacterCreationPage page for the characters/new route.
As noted, this only seems to happen when clicking browser "back" button. When clicking a link in-app, things seem to work.