0

In my react app I have a hook that handles resizing of the screen. The function returns an array of width and height.

function useDimensions() {
  const [size, setSize] = useState([window.innerWidth, window.innerHeight]);
  const [isSmScreen, setIsSmScreen] = useState(false);
  const [isLgScreen, setIsLgScreen] = useState(false);

  function handleResize() {
    const windowWidth = window.innerWidth;
    if (windowWidth < BREAKPOINTS.sm) {
      setIsXsScreen(true);
    } else if (windowWidth < BREAKPOINTS.lg) {
      setIsSmScreen(true);
    }

    setSize([window.innerWidth, window.innerHeight]);
  }

  useLayoutEffect(() => {
    // So it doesnt get called every pixel changed
    const debouncedResize = debounce(handleResize, 100);

    window.addEventListener('resize', debouncedResize);

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

  return size;
}

export default useDimensions;

And i call the hook in my react app like const [width] = useDimensions(). I also want to call the hook like const {isSmScreen} = useDimensions(). Is this possible and how can export it from the useDimensions hook

2
  • 4
    removeEventListener should be removing the debouncedResize, not handleResize Commented Jul 28, 2021 at 18:35
  • 2
    If the goal is to return various named properties, why not return an object instead of an array? Commented Jul 28, 2021 at 18:37

1 Answer 1

3

Sure, as an array is an object, you can define additional properties.

For instance:

size.isSmScreen = isSmScreen;
return size;

Or:

return Object.assign(size, {isSmScreen});

Whether this is a good idea, is debatable though. If I use a function to get an array, I would not expect that array to have other custom properties.

It would be more natural to return the array data as a single property of the returned object, like:

return { size, isSmScreen }

Then the caller must of course be aware of that. To only get the width, it could do:

let { size: [width] } = useDimensions();
Sign up to request clarification or add additional context in comments.

2 Comments

I was thinking something along the lines of declaring an array ie, const [width, height] = useDimensions(). And then declaring an object ie: const {isSmScreen} = useWindowSize(); 2 separate stuctures declare 2 separate things
Many options ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.