Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following hook using useLayoutEffect to register an event listener on the resize event of the window. I would like to add a throttle to it, say 1000ms, to call handleCanvasResize at most once per second.

What syntax should I use ?

useLayoutEffect(() => {
    window.addEventListener('resize', handleCanvasResize);
    return () => {
      window.removeEventListener('resize', handleCanvasResize);
    };
  }, [handleCanvasResize]);
question from:https://stackoverflow.com/questions/65940908/react-hooks-throttle-on-uselayouteffect

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
283 views
Welcome To Ask or Share your Answers For Others

1 Answer

You need to create a function reference which is throttled and then add it as a listener for your resize event. You can either use a library for throttle or implement your own.

const handleCanvasResizeThrottled = useMemo(() => _.throttle(handleCanvasResize, 1000), []);

useLayoutEffect(() => {
    window.addEventListener('resize', handleCanvasResizeThrottled);
    return () => {
      window.removeEventListener('resize', handleCanvasResizeThrottled);
    };
  }, [handleCanvasResizeThrottled]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...