Animating Elements with useRef
Show how to store a reference to a DOM element with useRef and then use that reference to animate the element using plain JavaScript without causing re-renders.
import { useRef, useEffect } from 'react';
Import useRef and useEffect hooks from React.
function AnimatedComponent() {
const elementRef = useRef(null);
useEffect(() => {
if (elementRef.current) {
const animation = elementRef.current.animate([
{ transform: 'translateX(0px)' },
{ transform: 'translateX(100px)' }
], {
duration: 1000, // 1 second
iterations: Infinity // Loop forever
});
return () => animation.cancel(); // Cleanup animation on unmount
}
}, []); // Empty dependency array means this effect runs once on mount
return <div ref={elementRef}>Animate Me!</div>;
}
Define an animated React component that uses the useRef hook to store a ref to the DOM element, then uses the useEffect hook to animate that element when the component mounts. The animation is infinite and will be cleaned up when the component unmounts.