Skip to content

Commit

Permalink
[@mantine/hooks] use-hash: Fix unexpected rerendering with hash witho…
Browse files Browse the repository at this point in the history
…ut `#` (#3097)

* Fix use-hash extra rerendering issue

Two bugs fixed:
* If you `setHash` to something that doesn't start with "#" it would be reflect that temporarily in `hash`
* `setHashValue` was being called multiple times (one in the listener and the set hash) resulting in the multiple renders

Result:
* `setHash` only rerenders the page once.

* Fix tests

window is not defined in ssr

* fix formatting

* Fix no-param-reassign and prefer-template
  • Loading branch information
hunterwilhelm committed Dec 4, 2022
1 parent 43e72a6 commit b2310e1
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/mantine-hooks/src/use-hash/use-hash.ts
Expand Up @@ -5,16 +5,20 @@ export function useHash() {
const [hash, setHashValue] = useState<string>('');

const setHash = (value: string) => {
window.location.hash = value;
setHashValue(value);
const valueWithHash = value.startsWith('#') ? value : `#${value}`;
window.location.hash = valueWithHash;
setHashValue(valueWithHash);
};

useWindowEvent('hashchange', () => {
setHashValue(window.location.hash);
const newHash = window.location.hash;
if (hash !== newHash) {
setHashValue(hash);
}
});

useEffect(() => {
setHash(window.location.hash);
setHashValue(window.location.hash);
}, []);

return [hash, setHash] as const;
Expand Down

0 comments on commit b2310e1

Please sign in to comment.