Get window dimension

Add window dimension specific check in Next.js

To get the window dimension (height and width) in nextjs, we can create the following ReactJs hook:

import { useState, useEffect } from 'react'

function getWindowDimensions() {
  const { innerWidth: width, innerHeight: height } = window
  return {
    width,
    height
  }
}

export default function useWindowDimensions() {
  if (typeof window !== 'undefined') {
    const [windowDimensions, setWindowDimensions] = useState(
      getWindowDimensions()
    )

    useEffect(() => {
      function handleResize() {
        setWindowDimensions(getWindowDimensions())
      }

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

    return windowDimensions
  } else {
    return {
      width: 0,
      height: 0
    }
  }
}

This hook is just like any other ReactJs hook, but it needs a check for window attribute while being used in Next.js.

To use this, you can add this hook into your component as follows:

import useWindowDimensions from 'hooks/dimension'
import Link from 'next/link'

export default function Tile({ article, highlighted }) {
  const { width } = useWindowDimensions()
  const isMobile = width < 550
  return (
    <>
      <Link href={`/articles/${article.slug}`} scroll={!isMobile}>
        <a className="link">
          <div className={`article-tile ${highlighted ? 'highlight' : ''}`}>
            {article.title}
          </div>
        </a>
      </Link>
    </>
  )
}