Thanks for the awesome article. I learned something and love hooks more and more ;) Adding throttling would make it an awesome solution as a drop in to various projects...
I couldn't make it work with lodashs throttling (there is no actual throttling in my solution). Here is what i got:
React.useEffect(()=>{consthandleWindowResize=()=>{console.log(count);// just a counter I added as a statesetWidth(window.innerWidth);setHeight(window.innerHeight);setCount(prevCount=>prevCount+1);};constthrottledHandleWindowResize=_.throttle(handleWindowResize,1000);window.addEventListener("resize",throttledHandleWindowResize);return()=>window.removeEventListener("resize",throttledHandleWindowResize);},[count]);
I guess it is because every time count changes a new event listener is attached and therefore throttling never happens. Am I right? What would be the solution? I guess it is something using useRef()? But I don't get it...
Hey Jannik, author here. Sorry for the very late reply I wasn't aware that my article was posted here 🙂 I'm glad you found it useful!
You are right, every time you are updating count your useEffect is going to rerun and a different event listener is going to be added every time. Moving your event listener outside of the effect should solve this for you!
You might also want to make use of useCallback, so that you can safely pass the function into the effect as a dependency - it would look something like this:
Thanks for the awesome article. I learned something and love hooks more and more ;) Adding throttling would make it an awesome solution as a drop in to various projects...
I couldn't make it work with lodashs throttling (there is no actual throttling in my solution). Here is what i got:
I guess it is because every time count changes a new event listener is attached and therefore throttling never happens. Am I right? What would be the solution? I guess it is something using
useRef()
? But I don't get it...Hey Jannik, author here. Sorry for the very late reply I wasn't aware that my article was posted here 🙂 I'm glad you found it useful!
You are right, every time you are updating
count
youruseEffect
is going to rerun and a different event listener is going to be added every time. Moving your event listener outside of the effect should solve this for you!You might also want to make use of
useCallback
, so that you can safely pass the function into the effect as a dependency - it would look something like this:Here are the useCallback docs, if you want to have a read about this 🙂Thanks for reading!