useWindowSize(๐Ÿ“บ)

August 04, 2020ย ย โ€ขย ย 1 min read

#4 hook of the week

To remind you of the purpose and goal of this week:

For a whole week I'll post a new hook every day. All hooks will support Server-Side Rendering (SSR) and have TypeScript implemented.

I will not describe the hooks in great detail, I'll just present them and show how it's implemented. Then you can do whatever you want with them.

Every hook is also available here, together with a range of other hooks.

View source

Showcase ๐Ÿ”ฅ

Resize your browser window and the size will be displayed below. It uses a 250 milliseconds wait timeout.

Current window size:
x

The hook ๐ŸŽฃ

Get window width and height with the opportunity to debounce the callback.

I'm using my isSSR utility and useResize() hook to get the window size when a resize is triggered.

import { useState, useCallback } from 'react';
import { isSSR } from './utils';
import { useResize } from './useResize';

export const useWindowSize = (
  wait: number = 250
): {
  width?: number;
  height?: number;
} => {
  const getWindowSize = useCallback(
    () => ({
      width: isSSR ? undefined : window.innerWidth,
      height: isSSR ? undefined : window.innerHeight
    }),
    []
  );
  const [windowSize, setWindowSize] = useState(getWindowSize);

  useResize(() => {
    setWindowSize(getWindowSize);
  }, wait);

  return windowSize;
};

Usage

When the width or height changes we'll debounce it with a 1000 milliseconds wait timeout and console.log() its sizes.

import React, { useEffect } from 'react';
import { useWindowSize } from './useWindowSize';

const Component = () => {
  const { width, height } = useWindowSize(1000);

  useEffect(() => {
    console.log(width, height);
  }, [width, height]);

  return null;
};

export default Component;

The end ๐Ÿ“บ

I hope you found this helpful.