wouter icon indicating copy to clipboard operation
wouter copied to clipboard

Redirect not triggering re-render when used with useHashLocation hook

Open sirianni opened this issue 3 years ago • 1 comments

There seems to be a bug when using useHashLocation (from the README) in tandem with Redirect.

This forked codepen reproduces the issue.

image

Even though the current location is /about, the components have not been rerendered.

I noticed this comment in https://github.com/molefrog/wouter/master/use-location.js. Is it possible something similar is needed in the useHashLocation example?

    // it's possible that an update has occurred between render and the effect handler,
    // so we run additional check on mount to catch these updates. Based on:
    // https://gist.github.com/bvaughn/e25397f70e8c65b0ae0d7c90b731b189
    checkForUpdates();

sirianni avatar Dec 21 '21 22:12 sirianni

@sirianni This is a demo I wrote before, I hope it will help you

cbbfcd avatar Dec 22 '21 06:12 cbbfcd

Hey @sirianni, thanks for pointing out to this issue. You can fix that by either implementing a similar check checkForUpdates() or using useSyncExternalStore hook (available in React 18, also has a shim for older versions):

const useHashLocation = () => {
  const location = useSyncExternalStore(
    (onChange) => {
      window.addEventListener("hashchange", onChange);
      return () => window.removeEventListener("hashchange", onChange);
    },
    // returns the current hash location (excluding the '#' symbol)
    () => window.location.hash.replace("#", "") || "/"
  );

  const navigate = useCallback((to) => (window.location.hash = to), []);
  return [location, navigate];
};

https://codesandbox.io/s/wouter-hash-location-w-usesyncexternalstore-kpkxgq?file=/index.js:262-723

I'll update the example in the README.

molefrog avatar Nov 15 '22 23:11 molefrog