📍디바운스
// App.tsx
import "./styles.css";
import { useState } from "react";
import { useDebounce } from "./useDebounce";
export default function App() {
const [keyword, setKeyword] = useState("");
const debouncedKeyword = useDebounce(keyword, 500);
return (
<div className="App">
<h1>Debounce + React + TypeScript</h1>
<h2>{debouncedKeyword}</h2>
<input type="text" onChange={(e) => setKeyword(e.target.value)} />
</div>
);
}
// useDebounce.tsx
import { useEffect, useState } from "react";
export const useDebounce = <T>(value: T, delay: number): T => {
const [debouncedValue, setDebouncedValue] = useState(value);
//
useEffect(() => {
const timer = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
console.log("clear timer");
clearTimeout(timer);
};
}, [value, delay]);
return debouncedValue;
};
📍코드 예시