Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/misc/isServer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const isServer = () => typeof window === 'undefined';
21 changes: 11 additions & 10 deletions src/useHash.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,26 @@
import { useCallback, useState } from 'react';
import useLifecycles from './useLifecycles';
import { useCallback, useEffect, useState } from 'react';
import { off, on } from './misc/util';
import { isServer } from './misc/isServer';

/**
* read and write url hash, response to url hash change
*/

export const useHash = () => {
const [hash, setHash] = useState(() => window.location.hash);
const [hash, setHash] = useState(() => (isServer() ? '' : window.location.hash));

const onHashChange = useCallback(() => {
setHash(window.location.hash);
}, []);

useLifecycles(
() => {
on(window, 'hashchange', onHashChange);
},
() => {
useEffect(() => {
if (isServer()) return;
on(window, 'hashchange', onHashChange);

return () => {
off(window, 'hashchange', onHashChange);
}
);
};
}, []);

const _setHash = useCallback(
(newHash: string) => {
Expand Down
15 changes: 15 additions & 0 deletions tests/useHash.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { renderHook, act } from '@testing-library/react-hooks';
import { useHash } from '../src/useHash';
import { isServer } from '../src/misc/isServer';

jest.mock('../src/misc/isServer');
const mockIsServer = isServer as jest.MockedFunction<typeof isServer>;

(global as any).window = Object.create(window);
let mockHash = '#';
Expand All @@ -18,9 +22,20 @@ Object.defineProperty(window, 'location', {
});

beforeEach(() => {
mockIsServer.mockReturnValue(false);
window.location.hash = '#';
});

test('returns an empty hash when rendered on the server', () => {
mockIsServer.mockReturnValue(true);
window.location.hash = '#abc';

const { result } = renderHook(() => useHash());

const hash = result.current[0];
expect(hash).toBe('');
});

test('returns current url hash', () => {
window.location.hash = '#abc';

Expand Down