Route Change Animations

Teach how to coordinate animations during route transitions by intercepting routing events and triggering animations at the right moment.
import { useLayoutEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { gsap } from 'gsap';

const useRouteChangeAnimation = () => {
  const location = useLocation(); // Hook to access the current location.
  useLayoutEffect(() => {
    // Define your animation, e.g., fading out the current page.
    gsap.fromTo('.page', { opacity: 1 }, { opacity: 0, duration: 0.5 });
    // Code to animate the new route content once the location changes.
      { opacity: 0 },
      { opacity: 1, duration: 0.5, delay: 0.5 }
  }, [location.pathname]); // Dependency array ensures animation runs on route change.

export default useRouteChangeAnimation;
This code snippet defines a custom React hook using 'useLayoutEffect' that triggers animations upon route changes. The animations are powered by GSAP (GreenSock Animation Platform). The hook listens for changes in the location's pathname and performs a fade-out animation followed by a fade-in for the new content. This custom hook can be imported and used in any component that needs route change animations.