Throttle Function (lodash Inspired) To Handle Resize Event Using React Hooks Only (with Sandbox)
Sorry for the long question, but I needed to make an introduction in order to make it clearer. I was in need of some code to toggle between my Headers components
Solution 1:
This isn't something i'd do with a hook. You can get it to work as a hook, but you're limiting yourself to only doing throttling inside components, when throttling is a more useful utility function than that, and hooks don't make it any easier or let you do anything extra.
If you don't want to import all of lodash, that's understandable, but you could implement something similar yourself. Lodash's throttle is a higher order function: you pass it in a function, and it returns you a new function that will only execute if the appropriate amount of time has passed since the last execution. The code to do that (without quite as many options and safety checks as lodash does) can be replicated like this:
constthrottle = (func, delay) => {
let inProgress = false;
return(...args) => {
if (inProgress) {
return;
}
inProgress = true;
setTimeout(() => {
func(...args); // Consider moving this line before the set timeout if you want the very first one to be immediate
inProgress = false;
}, delay);
}
}
To be used like this:
useEffect(() => {
const handleResize = throttle(() => {
setWindowSize(window.innerWidth);
}, 1000);
window.addEventListener("resize", handleResize);
return() =>window.removeEventListener("resize", handleResize);
}, []);
Post a Comment for "Throttle Function (lodash Inspired) To Handle Resize Event Using React Hooks Only (with Sandbox)"