TanStack / TanStack/router

useCanGoBack causes hydration error on page refresh

Open
#8,211 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
TypeScript
Stars
15.1k
Forks
1.9k
Avg merge
1d 20h
Merged PRs (30d)
143

Description

Which project does this relate to?

Router

Describe the bug

the useCanGoBack hook can throw a hydration error if a page is refreshed while there is history.

Complete minimal reproducer

https://github.com/babycourageous/tanstack-cangoback-hydration

Steps to Reproduce the Bug

there are 2 pages in the repro Start project - Page 1 and Page 2

  1. navigate to Page 2 from Page 1 by clicking the "Page 2" link
  2. Page 2 calls useCanGoBack and because of the browser history, it returns true as expected

Hello "/(test)/page2 can go back"! is displayed

  1. if you refresh the browser after navigating to Page 2, a hydration mismatch error is thrown and displayed in the console. It appears that the server renders canGoBack = false (empty history), but the client hydrates with true (history still contains Page1).
Expected behavior

I was expecting no hydration error - but maybe this is just a known limitation for using the hook.
A user in discord suggested conditionally rendering ui after a useEffect runs but this seems a little hacky.

If this is a known limitation, I'm curious how to perhaps safeguard the flash of false ui as well as avoiding the error

thanks!!

Screenshots or Videos

No response

Platform
  • Router / Start Version: "latest
  • OS: macOS
  • Browser: Brave
  • Browser Version: Brave 1.92.134 (Official Build) (x86_64)
  • Bundler: vite
  • Bundler Version: 8
Additional context

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the minimal reproducer and the useCanGoBack hook, focusing on the server and client values during a refresh of Page 2. Confirm the behavior with the listed navigation steps; done means the refresh no longer produces a hydration mismatch while the hook still reports the expected history state.

Written by the indexing model from the issue text.

Assessment

Tech stack
react, typescript, vite
Domain
frontend, web-dev
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
58/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.