0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【単発】Next.jsでも動作するuseHashフック

Last updated at Posted at 2024-08-16

なんで?

最初はreact-useを使っていたがwindow is not definedと出るのがうざすぎて自作するに至った
もしかしたらもっといい方法があるかもしれないけど一応供養

コード

import { useSyncExternalStore } from "react";

export default function useHash(): [string, (newHash: string) => void] {
  const hash = useSyncExternalStore(
    (callback) => {
      const listener = () => {
        callback();
      };
      window.addEventListener("hashchange", listener);
      return () => {
        window.removeEventListener("hashchange", listener);
      };
    },
    () => window.location.hash,
    () => ""
  );
  const setHash = (newHash: string) => {
    if (!window) return;
    window.location.hash = newHash;
  };
  return [hash, setHash];
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?