Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stable callback fn passed as ref to a Link gets called twice on every re-render #12705

Open
danhorvath opened this issue Jan 8, 2025 · 0 comments
Labels

Comments

@danhorvath
Copy link

I'm using React Router as a...

library

Reproduction

  1. Render a Link inside a component and pass a stable callback function as ref (e.g console.log). Feel free to do the same with a native element to see the normal behavior
  2. Trigger a re-render in the parent component, e.g by increasing a counter state

https://codesandbox.io/p/sandbox/react-router-link-ref-repro-forked-dhm6sn

System Info

System:
    OS: macOS 15.2
    CPU: (12) arm64 Apple M3 Pro
    Memory: 7.67 GB / 36.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.17.0 - ~/.nvm/versions/node/v20.17.0/bin/node
    npm: 10.8.2 - ~/.nvm/versions/node/v20.17.0/bin/npm
    pnpm: 9.15.3 - ~/.nvm/versions/node/v20.17.0/bin/pnpm
  Browsers:
    Chrome: 131.0.6778.205
    Edge: 131.0.2903.112
    Safari: 18.2
  npmPackages:
    react-router: 7.1.1 => 7.1.1

Used Package Manager

pnpm

Expected Behavior

The callback passed to the ref is only called when either the callback changes, or if the underlying node changes.

Actual Behavior

The callback gets called twice every time the Link is re-rendered, once with "null" and then with the actual anchor element. This can cause infinite re-renders in case the ref callback updates a state

This is probably because the refs are merged with a non-memoized mergeRefs function. Commonly that would be wrapped in a a useCallback.

ref={mergeRefs(forwardedRef, prefetchRef)}
target={target}

@danhorvath danhorvath added the bug label Jan 8, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant