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

[@mantine/hooks] Fixing use-hash extra rerendering issue #3097

Merged
merged 4 commits into from Dec 4, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 10 additions & 8 deletions src/mantine-hooks/src/use-hash/use-hash.ts
@@ -1,21 +1,23 @@
import { useState, useEffect } from 'react';
import { useState } from 'react';
import { useWindowEvent } from '../use-window-event/use-window-event';

export function useHash() {
const [hash, setHashValue] = useState<string>('');
const [hash, setHashValue] = useState<string>(() => window.location.hash);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will fail during ssr, window object does not exist.


const setHash = (value: string) => {
if (!value.startsWith("#")) {
value = "#" + value;
}
window.location.hash = value;
setHashValue(value);
};

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

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

return [hash, setHash] as const;
}