Skip to content

Instantly share code, notes, and snippets.

@yano3nora
Last active March 27, 2024 07:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yano3nora/f44f01b4c9656f83a229d0e4cdf0da62 to your computer and use it in GitHub Desktop.
Save yano3nora/f44f01b4c9656f83a229d0e4cdf0da62 to your computer and use it in GitHub Desktop.
[js: react-use] Custom react hooks library. #js #react

Overview

react-use - streamich.github.io streamich/react-use - github.com
react-use の実装から学ぶ custom hooks

useInterval

https://usehooks-ts.com/react-hook/use-interval

import { useState } from 'react'

import type { ChangeEvent } from 'react'

import { useInterval } from 'usehooks-ts'

export default function Component() {
  const [count, setCount] = useState<number>(0)
  const [isPlaying, setPlaying] = useState<boolean>(false)

  useInterval(
    () => {
      // ここに数 ms ごとにやりたいことを書く
      setCount(count + 1)
    },
    // null なら interval 停止、number なら interval の delay となる
    isPlaying ? delay : null,
  )

  return (
    <>
      <h1>{count}</h1>
      <button
        onClick={() => {
          setPlaying(!isPlaying)
        }}
      >
        {isPlaying ? 'pause' : 'play'}
      </button>
    </>
  )
}

useHover

useHover and useHoverDirty

import {useHover} from 'react-use';

const Demo = () => {
  const element = (hovered) =>
    <div>
      Hover me! {hovered && 'Thanks!'}
    </div>;
  const [hoverable, hovered] = useHover(element);

  return (
    <div>
      {hoverable}
      <div>{hovered ? 'HOVERED' : ''}</div>
    </div>
  );
};

useIntersection

https://github.com/streamich/react-use/blob/master/docs/useIntersection.md

import * as React from 'react'
import { useIntersection } from 'react-use'

const Demo = () => {
  const intersectionRef = React.useRef(null)
  const intersection = useIntersection(intersectionRef, {
    root: null,
    rootMargin: '0px',
    threshold: 1
  })

  return (
    <div ref={intersectionRef}>
      {intersection && intersection.intersectionRatio < 1
        ? 'Obscured'
        : 'Fully in view'}
    </div>
  )
}

useUnmount

https://github.com/streamich/react-use/blob/master/docs/useUnmount.md

  • useeffect の cleanup は、strict mode だと mount 時にも実行されてしまう
  • ↑ なときに onunmount 書きたいんじゃあーってならこれ
import { useUnmount } from 'react-use'

export const Demo = () => {
  useUnmount(() => alert('UNMOUNTED'))
  return null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment