visit
const input = document.querySelector(".custom-input");
// ❌ Before implementation
const searchResults = (event) => {
// Your core logic will be here!
console.log(event.target.value);
};
if (input) {
// Triggers for each keystrokes
input.addEventListener("input", searchResults);
}
// ✅ After implementation
const debounce = (cb, delay) => {
let debounceTime;
return (...args) => {
clearTimeout(debounceTime);
debounceTime = setTimeout(() => {
cb(...args);
}, delay);
};
};
if (input) {
// being debounced with a delay of 500 milliseconds
input.addEventListener("input", debounce(searchResults, 500));
}
Reference:
// Here, we implemented debouncing with React new hook called `useDeferredValue.`
export default function App() {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
return (
<>
<label>
Search albums:
<input value={query} onChange={e => setQuery(e.target.value)} />
</label>
</>
);
}
Reference:
const height = document.querySelector("#height");
const width = document.querySelector("#width");
// ❌ Before implementation
// invokes for each change
const handleResize = () => {
heightOutput.textContent = window.innerHeight;
widthOutput.textContent = window.innerWidth;
// Your business logic over here
};
(() => {
handleResize();
})();
window.addEventListener("resize", handleResize);
// ✅ After implementation
// invoke only once every 500 milliseconds (given delay)
const throttle = (cb, delay) => {
let throttling = false;
return (...args) => {
if (!throttling) {
throttling = true;
cb(...args);
setTimeout(() => {
throttling = false;
}, delay);
}
};
};
window.addEventListener("resize", throttle(handleResize, 500));
Reference:
import { useEffect, useRef } from "react";
export default function App() {
const heightRef = useRef();
const widthRef = useRef();
const throttle = (cb, delay) => {
let throttling = false;
return (...args) => {
if (!throttling) {
throttling = true;
cb(...args);
setTimeout(() => {
throttling = false;
}, delay);
}
};
};
useEffect(() => {
const handleResize = () => {
heightRef.current.textContent = window.innerHeight;
widthRef.current.textContent = window.innerWidth;
// Your business logic over here
};
window.addEventListener("resize", throttle(handleResize, 500));
return () => {
window.removeEventListener("resize", throttle(handleResize, 500));
};
}, []);
return (
<div>
<p>
Current window width: <span ref={widthRef}></span>
</p>
<p>
Current window height: <span ref={heightRef}></span>
</p>
</div>
);
}
Reference:
Stay curious; keep coding!
Also published .