Alessandro Alghisi
Alessandro Alghisi

Reputation: 21

Basically I'm trying to add an EventListener for resize and

So here is the code ...

function getWindowDimensions() {
  const { innerWidth: width, innerHeight: height } = window;
  return {
    width,
    height
  };
}

 let minNumberOfCards = Math.round(window.innerWidth / 120);
 const [windowDimensions, setWindowDimensions] = React.useState(getWindowDimensions());

    React.useEffect(() => {
      function handleResize() {
        setWindowDimensions(getWindowDimensions());
      }

      window.addEventListener('resize', handleResize);
      return () => window.removeEventListener('resize', handleResize);
    }, [windowDimensions,]);

The issue I'm facing is that I need to compute the number of cards to be displayed and I get the a really messy result :|. Since addEventListener is an async thingy. What I tried is minNumberOfCards = Math.round(windowDimensions.width/ 120); buuuut again since it's async I get the correct number after a while time when my initial numbers I set kicks in. Basically I've set a var minNumberOfCards to be default 9 ( for example ).

The expected result would be to have the minNumberOfCards depending on the screen width. That's it !!!!! Any ideas/solutions on how can I achieve this without causing lots of re-renderings ?

Upvotes: 0

Views: 106

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53884

Its a perfect use case for debounce or throttle:

import debounce from 'lodash.debounce';

const App = () => {
  const [windowDimensions, setWindowDimensions] = useState('Change Window Size');

  const [minNumberOfCards, setMinNumberOfCards] = useState(
    Math.round(window.innerWidth / 120)
  );

  useEffect(() => {
    // Better add a listener and only change the minNumberOfCards
  },[...]);

  useEffect(() => {
    const handleResize = () => setWindowDimensions(getWindowDimensions());
    const debouncedHandleResize = debounce(handleResize, 500);

    window.addEventListener('resize', debouncedHandleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, [windowDimensions]);
  return (
    <FlexBox>
      <pre>{JSON.stringify(windowDimensions, null, 2)}</pre>
    </FlexBox>
  );
};

Try changing the window size in the next sandbox:

Edit react-antd-styled-template

Please refer to Debouncing and Throttling Explained Through Examples

Upvotes: 1

Related Questions