Skip to content
Advertisement

JS return an array and an object from function

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

Advertisement

Answer

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();
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement