'Set the initial value of Framer motion useCycle based on screen width

I have a sidebar and I toggle its visibility using Framer Motion's useCycle hook, but it should be open by default on desktop (window width > 480px) and closed by default on mobile.

Since I'm dealing with JS, I used this hook (found online) to determine the width of the window and see whether it is mobile (< 480px) or not (> 480px):

import { useEffect, useState } from "react";

export function useMediaQuery(query) {
  const [matches, setMatches] = useState(false);

  useEffect(() => {
    const media = window.matchMedia(query);
    if (media.matches !== matches) {
      setMatches(media.matches);
    }
    const listener = () => {
      setMatches(media.matches);
    };
    media.addListener(listener);
    return () => media.removeListener(listener);
  }, [matches, query]);

  return matches;
}

export const useIsMobile = () => useMediaQuery("(max-width: 480px)");

And this is how I toggle the sidebar visibility:

const [sidebarIsOpen, toggleSidebar] = useCycle(true, false);

The order of true/false is important and defines the initial state.

I tried to set the initial value of sidebar visibility using this hook, but it doesn't work:

const isMobile = useIsMobile();
const [sidebarIsOpen, toggleSidebar] = useCycle(isMobile, !isMobile);

What am I doing wrong here?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source