useHash
useHash (URL 해시 관리)
useHash 훅은 브라우저의 URL 해시를 상태로 관리하고 변경할 수 있게 해줘요. 해시 값을 상태처럼 읽고 쓸 수 있어요.
출처: 문서
본문
useHash 훅을 이용해 URL 해시를 읽거나 변경할 수 있어요.
import { useHash, randomId } from '@mantine/hooks';
import { Button, Text, Code } from '@mantine/core';
function Demo() {
const [hash, setHash] = useHash();
return (
<>
<Button onClick={() => setHash(randomId())}>Set hash to random string</Button>
<Text>Current hash: {hash}</Text>
</>
);
}
초기 상태 값 (Initial state value)
기본적으로 useHash는 useEffect에서 값을 가져와요. 훅이 호출되는 즉시 초기 값을 얻고 싶다면 getInitialValueInEffect를 false로 설정하세요. 이 옵션은 서버 사이드 렌더링과 호환되지 않으므로, 앱이 클라이언트 전용일 때만 사용할 수 있어요.
import { Button } from '@mantine/core';
import { useHash } from '@mantine/hooks';
function Demo() {
const [hash, setHash] = useHash({ getInitialValueInEffect: false });
return (
<Button onClick={() => setHash('new-hash')}>Change hash</Button>
);
}
정의 (Definition)
interface UseHashOptions {
getInitialValueInEffect?: boolean;
}
type UseHashReturnValue = [string, (value: string) => void];
function useHash(options?: UseHashOptions): UseHashReturnValue
Exported types
UseHashOptions와 UseHashReturnValue 타입은 @mantine/hooks에서 내보내져요.
import { UseHashOptions, UseHashReturnValue } from '@mantine/hooks';
더 알아보기 (Learn more)
- useFetch — 데이터 불러오기
- useHeadroom — 스크롤 기반 헤더 표시/숨김