Skip to content

Instantly share code, notes, and snippets.

Last active January 21, 2022 13:02
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save gragland/4e3d9b1c934a18dc76f585350f97e321 to your computer and use it in GitHub Desktop.
import { useState, useEffect } from 'react';
// Usage
function App() {
const size = useWindowSize();
return (
{size.width}px / {size.height}px
// Hook
function useWindowSize() {
// Initialize state with undefined width/height so server and client renders match
// Learn more here:
const [windowSize, setWindowSize] = useState({
width: undefined,
height: undefined,
useEffect(() => {
// Handler to call on window resize
function handleResize() {
// Set window width/height to state
width: window.innerWidth,
height: window.innerHeight,
// Add event listener
window.addEventListener("resize", handleResize);
// Call handler right away so state gets updated with initial window size
// Remove event listener on cleanup
return () => window.removeEventListener("resize", handleResize);
}, []); // Empty array ensures that effect is only run on mount
return windowSize;
Copy link

gragland commented Jul 30, 2020

@lax4mike thanks for pointing out the SSR issue! I've updated this gist and the post.

Copy link

ivanjeremic commented Dec 5, 2021

change the useEffect to useLayoutEffect because you see a flicker before it's set in some cases. useLayoutEffect is definitely the way to go here. Here an example where a div is centered based on the body, if you change it to a normal useEffect you will see it flicker.

Copy link

mimiqkz commented Jan 21, 2022

Long time has passed , why haven't this been updated with debounce or throttle ?

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