Skip to content

Commit

Permalink
[@mantine/hooks] use-hash: Add option to retrieve value initially wit…
Browse files Browse the repository at this point in the history
…hout `useEffect` (#5140)
  • Loading branch information
rtivital committed Nov 7, 2023
1 parent 557f091 commit 5f2b215
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
19 changes: 18 additions & 1 deletion docs/pages/hooks/use-hash.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,25 @@ and allows changing it with `setHash` function:

<Demo data={HooksDemos.useHashDemo} />

## Initial state value

By default, `use-hash` will retrieve value in `useEffect`. If you want to get initial value
as soon as hook is called, set `getInitialValueInEffect` to `false`. Note that this option is
not compatible with server side rendering – you can only use it if your app is client-side only.

```tsx
import { useHash } from '@mantine/hooks';

function Demo() {
const [hash, setHash] = useHash({ getInitialValueInEffect: false });
return <Button onClick={() => setHash('new-hash')}>Change hash</Button>;
}
```

## Definition

```tsx
function useHash(): readonly [string, (value: string) => void];
function useHash(options: {
getInitialValueInEffect?: boolean;
}): readonly [string, (value: string) => void];
```
14 changes: 11 additions & 3 deletions src/mantine-hooks/src/use-hash/use-hash.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import { useState, useEffect } from 'react';
import { useWindowEvent } from '../use-window-event/use-window-event';

export function useHash() {
const [hash, setHashValue] = useState<string>('');
interface UseHashOptions {
getInitialValueInEffect?: boolean;
}

export function useHash({ getInitialValueInEffect = false }: UseHashOptions = {}) {
const [hash, setHashValue] = useState<string>(
getInitialValueInEffect ? window.location.hash || '' : ''
);

const setHash = (value: string) => {
const valueWithHash = value.startsWith('#') ? value : `#${value}`;
Expand All @@ -18,7 +24,9 @@ export function useHash() {
});

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

return [hash, setHash] as const;
Expand Down

0 comments on commit 5f2b215

Please sign in to comment.