고유한 useDebouncedEffect 후크를 만들어 모든 효과를 디바운스합니다.
5184 단어 reactwebdevhooksjavascript
이 게시물에서는 모든 효과를 디바운스하는 사용자 지정 React 후크를 작성합니다!
후크 작성
우리의 훅은 useEffect 훅처럼 보여야 합니다. 단, 디바운스하려는 시간에 대해 추가 매개변수time를 취해야 한다는 점이 다릅니다. 따라서 매개변수는 다음과 같아야 합니다.
디바운스 동작 달성
디바운스하기 위해 사용자가 제공한
setTimeout 와 함께 time 를 사용합니다. 문제는 타임아웃이 실행되기 전에 효과가 다시 실행되면 타임아웃을 취소하고 새 타임아웃을 시작해야 한다는 것입니다. clearTimeout 와 함께 정리 기능을 사용하여 이를 수행할 수 있습니다. 따라서 우리의 후크는 다음과 같습니다.import { useEffect } from "react";
function useDebouncedEffect(fn, deps, time) {
const dependencies = [...deps, fn, time]
useEffect(() => {
const timeout = setTimeout(fn, time);
return () => {
clearTimeout(timeout);
}
}, dependencies);
}
작동 중인 후크 보기
이 예제에서는 사용자가 텍스트 상자에서 입력을 중지할 때를 기반으로 디바운스된 지연에 일부 상태를 설정합니다. 여기 코드가 있습니다!
function App() {
const [text, setText] = useState("")
const [debounced, setDebounced] = useState("")
useDebouncedEffect(() => {
setDebounced(text);
}, [text], 1000)
return (
<div className="App">
<input onChange={e => {
setText(e.target.value)
}} value={text}
/>
<p>{debounced}</p>
</div>
);
}
그리고 실제로 사용해 보면... 작동합니다!
Reference
이 문제에 관하여(고유한 useDebouncedEffect 후크를 만들어 모든 효과를 디바운스합니다.), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://dev.to/nas5w/debounce-any-effect-by-creating-your-own-usedebouncedeffect-hook-38hd
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
function App() {
const [text, setText] = useState("")
const [debounced, setDebounced] = useState("")
useDebouncedEffect(() => {
setDebounced(text);
}, [text], 1000)
return (
<div className="App">
<input onChange={e => {
setText(e.target.value)
}} value={text}
/>
<p>{debounced}</p>
</div>
);
}
Reference
이 문제에 관하여(고유한 useDebouncedEffect 후크를 만들어 모든 효과를 디바운스합니다.), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/nas5w/debounce-any-effect-by-creating-your-own-usedebouncedeffect-hook-38hd텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)