Hey everyone,
I've been doing some searching around the forum about doing complex timeline based animations with React. I have found some answers that I don't think are up to date as they don't currently work. For example:
Applying `const timeline = gsap.timeline()` with `useEffect()` will reset the timeline when the component re-renders as it redefines the `const`. I have decided to go for `const timeline = useMemo(() => gsap.timeline({ paused: true }), [])`. I'm unsure if this is best practice, but it isn't giving me any problems really.
The one that is giving me a problem however is
const imageRef = useRef(null)
const [hovered, setHovered] = useState(false)
const timeline = useMemo(() => gsap.timeline({ paused: true }), [])
useEffect(() => {
timeline
.fromTo(
imageRef.current,
{
clipPath: 'polygon(0% 100%, 100% 100%, 100% 100%, 0% 100%)',
rotate: -10,
y: 20,
autoAlpha: 0,
},
{
clipPath: 'polygon(0% 65%, 100% 35%, 100% 100%, 0% 100%)',
rotate: 0,
y: 5,
autoAlpha: 0.4,
duration: 0.15,
}
)
.to(imageRef.current, {
clipPath: 'polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%)',
rotate: 5,
autoAlpha: 1,
y: 0,
})
return () => {
timeline.kill()
}
}, [timeline])
function onEnter() {
setHovered(true)
timeline.play()
}
function onLeave() {
setHovered(false)
timeline.reverse()
}
Because React in development mode invokes a double render, when you fire `onEnter` the timeline skips, this doesn't happen in the deployed site because of the lack of double render. But I'm unsure exactly what it's happening.
Is `useMemo` the incorrect hook to be using for this use case? I tried doing `useRef` then assigning gsap to `useRef.current` but that completely stopped the page from rendering giving a timeout.
Thanks,
Tom
PS:
Please release an official React module, I will love you forever!