🥦

React Debounceを実現するための三つ方法

2022/10/31に公開
  1. useEffectを活用します
import { useEffect, useState } from "react";

const delay = 2000

function Debounce() {
  const [value, setValue] = useState("")

  const handleSetValue = (e) => {
    setValue(e.target.value)
  }

  useEffect(() => {
    const id = setTimeout(() => {
      console.log('d');
    },delay)

    return () => {
      clearTimeout(id);
    }
  }, [value])

  return (
    <div className='container'>
      <p>value:{value}</p>
      <input onChange={e=>handleSetValue(e)}/>
    </div>
  );
}

export default Debounce;
  1. bindを活用します
import { useState } from "react";

const handleA = (delay, timeOutId, previousTime, currentTime) => {
  if (currentTime - previousTime <= delay) {
    clearTimeout(timeOutId);
  }
}

let doHandleA

const delay = 2000

function Debounce() {
  const [value, setValue] = useState("")

  const handleSetValue = (e) => {

    const now = new Date().getTime();

    if (doHandleA != null) {
      doHandleA(now)
    }

    const timeOutId = setTimeout(() => {
      console.log("do")
      setValue(e.target.value)
    }, delay)

    doHandleA = handleA.bind(null, delay, timeOutId, now)
  }

  return (
    <div className='container'>
      <p>value:{value}</p>
      <input onChange={e=>handleSetValue(e)}/>
    </div>
  );
}

export default Debounce;
  1. closureを活用します
import { useCallback, useState } from "react";

const delay = 500

const useDebounce = (delay) => {
  let id
  return function(fn) {
    clearTimeout(id)
    id = setTimeout(fn,delay)
  }
}

function Debounce() {
  const [value, setValue] = useState("")

  const doDebounce = useCallback(useDebounce(delay),[])
  const handleSetValue = (e) => {
    doDebounce(() => {
      setValue(e.target.value)
    })
  }

  return (
    <div className='container'>
      <p>value:{value}</p>
      <input onChange={e=>handleSetValue(e)}/>
    </div>
  );
}

export default Debounce;

チュートリアル動画

  • useEffectを活用します

https://www.youtube.com/watch?v=EMF8XZBgruk&t=1s

  • bindを活用します

https://www.youtube.com/watch?v=t2D3Kb7d9hY&t=5s

  • closureを活用します

https://www.youtube.com/watch?v=t-YmZP5nXOU&t=3s

Discussion