0

How can I use window resize event on react.js?

It works well, but sometimes it's in the wrong place when I reduce the size quickly by mouse.

that is my code

  window.addEventListener(
    'resize',
    () => {
      setSize(Math.ceil(nameInput?.current?.offsetWidth));
    },
    true,
  );
  • Hello, welcome to SO. Please add more details to your question, so we can help you better. Take a look [here](https://stackoverflow.com/help/minimal-reproducible-example) to produce a minimal working example. You can also use [codesandbox](https://codesandbox.io/). – Abdulrahman Ali Oct 20 '22 at 08:14
  • Since `setSize` is probably an updater function of `useState`, which is asynchronous, I would guess that the you cann't guarantee that the `resize` event and state will be always in sync. – HynekS Oct 20 '22 at 10:50
  • 1
    You can *debounce* the resize event – wait a few ms after the event ended and *then* update the state. See `debounce` function. Also, you can check libraries that implements resize hook somehow (e. g. https://github.com/ZeeCoder/use-resize-observer) – you may not want to reinvent the wheel… – HynekS Oct 20 '22 at 10:52
  • Does this answer your question? [Rerender view on browser resize with React](https://stackoverflow.com/questions/19014250/rerender-view-on-browser-resize-with-react) – Alpha Oct 20 '22 at 11:40

0 Answers0