Skip to content

How to have an initial animation based off of window width in React? #3020

Closed Answered by mattbal
mattbal asked this question in Q&A
Discussion options

You must be logged in to vote

OK, I figured out two solutions:

  1. Render nothing until first render has passed, then get the width, and then render everything
// hooks.tsx

import { useEffect, useState } from 'react';

export function useScreenWidth() {
  const [width, setWidth] = useState<undefined | number>(undefined);

  useEffect(() => {
    function handleResize() {
      setWidth(window.innerWidth);
    }

    handleResize();

    window.addEventListener('resize', handleResize);

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

  return width;
}
// App.tsx

export default function Home() {
  const width = useScreenWidth();
  const [canShow, setCanShow] = useState(false);

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
1 reply
@mattbal
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by mattbal
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants