Jump to content
Search Community

Using useGSAP makes my application lag significantly. However, when I switch to useEffect, everything works fine.

Eduardas
Moderator Tag

Recommended Posts

Posted
const DotCursor: React.FC = () => {
  const dotRef = useRef<HTMLDivElement>(null);
  const { clientX, clientY } = useMousePosition();
  const [isVisible, setIsVisible] = useState(false);
 
  const handleMouseEnter = () => {
    setIsVisible(true);
  };
 
  const handleMouseLeave = () => {
    setIsVisible(false);
  };
  const handleMouseMove = () => {
    setIsVisible(true);
  };
 
  useGSAP(
    () => {
      const dot = dotRef.current;
 
      if (!dot) return;
 
      window.addEventListener("mousemove", handleMouseMove);
      document.addEventListener("mouseenter", handleMouseEnter);
      document.addEventListener("mouseleave", handleMouseLeave);
 
      const animateDot = () => {
        gsap.set(dot, {
          x: clientX,
          y: clientY,
        });
      };
      gsap.ticker.add(animateDot);
      return () => {
        window.removeEventListener("mousemove", handleMouseMove);
        document.removeEventListener("mouseenter", handleMouseEnter);
        document.removeEventListener("mouseleave", handleMouseLeave);
        gsap.ticker.remove(animateDot);
      };
    },
    { dependencies: [clientX, clientY] }
  );
 
  return (
    <div
      ref={dotRef}
      className="dot-cursor bg-orange-700"
      style={{
        opacity: isVisible ? 1 : 0,
        position: "fixed",
        width: "10px",
        height: "10px",
        border: "solid 1px black",
        borderRadius: "20%",
        pointerEvents: "none",
        transform: "translate(-50%, -50%)",
        zIndex: 9999,
      }}
    />
  );
};
 
export default DotCursor;
Posted

Hi @Eduardas and welcome to the GSAP Forums!

 

Our useGSAP hook is being used in several sites and demos all over the web, if there was a real performance problem these forums would be swamped with threads and complaints in that regard.

 

I think your main problem stems from the fact that you're updating the state on every mouse move which re-renders everything. I would avoid that if I was you, there is no need to keep that in a state or even use a custom hook IMHO, this approach is far simpler and doesn't create any performance issue:

See the Pen Rwvdowy by GreenSock (@GreenSock) on CodePen.

 

Hopefully this helps.

Happy Tweening!

Posted

Thanks for quick answer ! 

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...