😀

便利なReactカスタムフックが用意しているusehooks-tsとは

2025/02/15に公開

Reactカスタムフックライブラリのusehooks-tsの使い方について紹介します。

usehooks-tsとは

便利なhookがたくさん入っているReactフックライブラリです。
フックはDRY (Don't Repeat Yourself) の原則に基づいて構築されており、導入手順もわかりやすいです。

npm install usehooks-ts

で導入可能です。

引用: https://usehooks-ts.com/

usehooks-ts使い方

便利そうなReactフックを何個か紹介します。

1. useCopyToClipboard

テキストをクリップボードにコピーするカスタムフックです。
この例だと、A,B,Cの3種類のボタンがあり、Aのボタンを押すと、
Aの文字がコピーされた状態になります。
何かをテキストをコピーしたい処理を作りたい場合は、かなり楽に作れます。

import { useCopyToClipboard } from 'usehooks-ts'

export default function Component() {
  const [copiedText, copy] = useCopyToClipboard()

  const handleCopy = (text: string) => () => {
    copy(text)
      .then(() => {
        console.log('Copied!', { text })
      })
      .catch(error => {
        console.error('Failed to copy!', error)
      })
  }

  return (
    <>
      <h1>Click to copy:</h1>
      <div style={{ display: 'flex' }}>
        <button onClick={handleCopy('A')}>A</button>
        <button onClick={handleCopy('B')}>B</button>
        <button onClick={handleCopy('C')}>C</button>
      </div>
      <p>Copied value: {copiedText ?? 'Nothing is copied yet!'}</p>
    </>
  )
}

引用:https://usehooks-ts.com/react-hook/use-copy-to-clipboard

2.useEventListener

イベントリスナーをアタッチするカスタムフックです。
この例だと、windowのscrollイベントを監視するscrollとdocumentのvisibilitychangeを監視するvisibilitychangeと<button>のclickイベントを監視するclickの3種類のイベントリスナーを登録します。
イベントリスナーの登録の処理だと通常だと長い処理になってしまうので、短縮できるのはかなり便利です。

import { useRef } from 'react'

import { useEventListener } from 'usehooks-ts'

export default function Component() {
  // Define button ref
  const buttonRef = useRef<HTMLButtonElement>(null)
  const documentRef = useRef<Document>(document)

  const onScroll = (event: Event) => {
    console.log('window scrolled!', event)
  }

  const onClick = (event: Event) => {
    console.log('button clicked!', event)
  }

  const onVisibilityChange = (event: Event) => {
    console.log('doc visibility changed!', {
      isVisible: !document.hidden,
      event,
    })
  }

  // example with window based event
  useEventListener('scroll', onScroll)

  // example with document based event
  useEventListener('visibilitychange', onVisibilityChange, documentRef)

  // example with element based event
  useEventListener('click', onClick, buttonRef)

  return (
    <div style={{ minHeight: '200vh' }}>
      <button ref={buttonRef}>Click me</button>
    </div>
  )
}

https://usehooks-ts.com/react-hook/use-event-listener

3.useLocalStorage

ローカルストレージを使用するカスタムフックです。
この例だと、setValueの数値の値がローカルストレージに保存されるようです。

import { useLocalStorage } from "usehooks-ts";

export default function Component() {
  const [value, setValue, removeValue] = useLocalStorage("test-key", 0);

  return (
    <div>
      <p>Count: {value}</p>
      <button
        onClick={() => {
          setValue((x: number) => x + 1);
        }}
      >
        Increment
      </button>
      <button
        onClick={() => {
          setValue((x: number) => x - 1);
        }}
      >
        Decrement
      </button>
      <button
        onClick={() => {
          removeValue();
        }}
      >
        Reset
      </button>
    </div>
  );
}

引用: https://usehooks-ts.com/react-hook/use-local-storage

4.use-unmount

このカスタムフックは、アンマウント時の処理を書くことが可能です。

import { useUnmount } from 'usehooks-ts'

export default function Component() {
  useUnmount(() => {
    // Cleanup logic here
  })

  return <div>Hello world</div>
}

引用: https://usehooks-ts.com/react-hook/use-unmount

5.useDarkMode

このカスタムフックは、ダークモードの切り替えの処理を書くことが可能です。

import { useDarkMode } from "usehooks-ts";

export default function Component() {
  const { isDarkMode, toggle, enable, disable } = useDarkMode();

  return (
    <div>
      <p>Current theme: {isDarkMode ? "dark" : "light"}</p>
      <button onClick={toggle}>Toggle</button>
      <button onClick={enable}>Enable</button>
      <button onClick={disable}>Disable</button>
    </div>
  );
}

引用: https://usehooks-ts.com/react-hook/use-dark-mode

まとめ

他にも様々なカスタムフックが用意されているので、
色々見てみると面白いです。
ぜひ使ってみてください。

Discussion