Skyler Gunn
Skyler Gunn

Reputation: 59

Next.js can't get window size without bad hook call or undefined window?

I've been trying to dynamically size an image in a next.js app (to make it work with different screen sizes), but the different approaches I've tried and seen have all given me either invalid hook call error or undefined window error.

const [width, setWidth]   = useState(typeof window === 'undefined' ? 0 : window.innerWidth);
const [height, setHeight] = useState(typeof window === 'undefined' ? 0 : window.innerHeight);
const updateDimensions = () => {
    if (typeof window !== 'undefined') {
    setWidth(window.innerWidth);
    setHeight(window.innerHeight);
    }
}
useEffect(() => {
    window.addEventListener("resize", updateDimensions);
    return () => window.removeEventListener("resize", updateDimensions);
}, []);

Upvotes: 1

Views: 3522

Answers (2)

Viacheslav Bakshaev
Viacheslav Bakshaev

Reputation: 272

Try Hooks like that

const useWidth = () => {
  const [width, setWidth] = useState(0)
  const handleResize = () => setWidth(window.innerWidth)
  useEffect(() => {
      handleResize()
      window.addEventListener('resize', handleResize)
      return () => window.removeEventListener('resize', handleResize)
      // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  return width
}

Upvotes: 0

Felix Haeberle
Felix Haeberle

Reputation: 1606

If you want to run the outer function in the useEffect hook, you can try to give it as callback argument, so that it looks like this:

useEffect(() => {
    window.addEventListener("resize", updateDimensions);
    return () => window.removeEventListener("resize", updateDimensions);
}, [updateDimensions]);

Reason for this could be that the component is server-side rendered and can't pick up the outer function as a dependency.

Upvotes: 1

Related Questions