Instantly share code, notes, and snippets.

Embed
What would you like to do?
import { useState, useEffect } from 'react';
// Usage
function App() {
const size = useWindowSize();
return (
<div>
{size.width}px / {size.height}px
</div>
);
}
// Hook
function useWindowSize() {
const isClient = typeof window === 'object';
function getSize() {
return {
width: isClient ? window.innerWidth : undefined,
height: isClient ? window.innerHeight : undefined
};
}
const [windowSize, setWindowSize] = useState(getSize);
useEffect(() => {
if (!isClient) {
return false;
}
function handleResize() {
setWindowSize(getSize());
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []); // Empty array ensures that effect is only run on mount and unmount
return windowSize;
}
@mattfysh

This comment has been minimized.

mattfysh commented Oct 31, 2018

You could pass a function into useState, so the initial state is calculated only once (and not on each render), i.e:

const [windowSize, setWindowSize] = useState(getSize)
@gragland

This comment has been minimized.

Owner

gragland commented Oct 31, 2018

@mattfysh Good catch! Will update shortly.

@AndyBarron

This comment has been minimized.

AndyBarron commented Oct 31, 2018

Couldn't we declare isClient and getSize in the module scope so that they're only checked/allocated once? I would also be a fan of returning [width, height] as a tuple, but that's super subjective.

Also, the useEffect callback unconditionally accesses window, so the isClient check wouldn't prevent you from crashing in a non-client environment.

import { useState, useEffect } from 'react';

// Usage
function App() {
  const [width, height] = useWindowSize();

  return (
    <div>
      {width}px / {height}px
    </div>
  );
}

// Helpers
const IS_CLIENT = typeof window === 'object';
const getSize = IS_CLIENT ?
  () => [window.innerWidth, window.innerHeight] :
  () => [undefined, undefined];

// Hook
function useWindowSize() {
  const [windowSize, setWindowSize] = useState(getSize);

  useEffect(() => {
    if (!IS_CLIENT) {
      return;
    }
    
    function handleResize() {
      setWindowSize(getSize());
    };
    
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []); // Empty array ensures that effect is only run on mount and unmount

  return windowSize;
}
@gragland

This comment has been minimized.

Owner

gragland commented Nov 2, 2018

@AndyBarron Thanks, fixed the issue with isClient not being checked within useEffect. And agree that isClient and getSize should probably be in module scope. For the time being, I'm trying to keep the usage and hook functions fairly self contained so it's easier to copy one or the other into a project without missing anything.. but I'll likely resolve that soon by breaking the two up into separate code blocks, in which case I'll then move stuff out into module scope where it makes sense. Really appreciate the detailed feedback you've been giving on all the hooks!

@mattfysh

This comment has been minimized.

mattfysh commented Nov 5, 2018

Also, the useEffect callback unconditionally accesses window, so the isClient check wouldn't prevent you from crashing in a non-client environment.

Given that useEffect somewhat relates to componentDidMount and componentDidUpdate, does this mean they are not executed in server-side rendering contexts? My hunch is that they aren't invoked, and the access of window should be okay?

@ianobermiller

This comment has been minimized.

ianobermiller commented Nov 9, 2018

I suggest moving handleResize into useEffect as in @AndyBarron's example

@gustavoguichard

This comment has been minimized.

gustavoguichard commented Nov 12, 2018

An optional debounce value would fit nicely here ;)

@gragland

This comment has been minimized.

Owner

gragland commented Nov 20, 2018

@yazeedb

This comment has been minimized.

yazeedb commented Nov 25, 2018

@gragland Thanks for this hook, I'm using it on a project!
May I write a brief blog post on it? Will link back to you and useHooks.com

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment