🥦
React Debounceを実現するための三つ方法
- 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;
- 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;
- 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を活用します
- bindを活用します
- closureを活用します
Discussion