I have a component that I want to edit some style dynamically. When I enter the component I want it to smoothly grow and when I leave I want it to smoothly shorten.
This is my code:
const easing = 0.1;
const outScale = 0.6;
const inScale = 1;
let targetScale = outScale;
let elementScale = targetScale;
let innerScale = 1 / elementScale;
const [parentTransformStyle, setParentTransformStyle] = useState(
`scale(${elementScale})`
);
const [innerTransformStyle, setInnerTransformStyle] = useState(
`scale(${innerScale})`
);
const requestRef = useRef();
const onPointOverEvent = () => {
targetScale = inScale;
console.log("over", inScale, targetScale);
};
const onPointerOutEvent = () => {
targetScale = outScale;
console.log("out", outScale, targetScale);
};
const animate = () => {
console.log("animate", targetScale);
elementScale += (targetScale - elementScale) * easing;
innerScale = 1 / elementScale;
setParentTransformStyle(`scale(${elementScale})`);
setInnerTransformStyle(`scale(${innerScale})`);
requestAnimationFrame(animate);
};
useEffect(() => {
requestRef.current = requestAnimationFrame(animate);
return () => cancelAnimationFrame(requestRef.current);
}, []);
The variable targetScale is supposed to be updated when the mouse hovers in the element and when the mouse leaves the element.
If I print the value inside the event listeners, the value is correct. However inside the animate function, it has the initial value. Can someone point me to what I'm missing?