본문 바로가기
Frontend/- Framer motion

Framer motion : useTime & useAnimate에 대해서

by 코딩쥐 2024. 10. 6.

useTime

렌더링 이후의 시간을 밀리초 단위로 업데이트하여 시간 기반의 애니메이션을 구현하는 데 유용하게 사용된다. 이를 통해 애니메이션의 속도나 변화를 시간에 따라 동적으로 조정할 수 있다.

  • const time = useTime();
import { motion, useTime, useTransform } from "framer-motion";

export default function Comp07() {
    const time = useTime();

    const rotate = useTransform(
        time,
        // 0초에서 2초는 0도에서 90도로 회전, 2초에서 4초는 90도에서 360도 회전
        [0, 2000, 4000],
        [0, 90, 360], 
        // 지정한 입력 범위 내에서만 출력한다.
        { clamp: true }
    );

    const borderRadius = useTransform(
        time,
        // 0에서 2초는 border radius가 0에서 5, 2초에서 4초는 5에서 50으로 변경
        [0, 1000, 4000],
        [0, 5, 50],
        {clamp: true}
    )


    return (
        <div style={{ display: "flex", justifyContent: "center" }}>
            <motion.div
                style={{
                    rotate,
                    borderRadius,
                    backgroundColor: "green",
                    width: 100,
                    height: 100,
                    textAlign: "center",
                }}
            >
                Box
            </motion.div>
        </div>
    );
}


useAnimate

motion 구성 요소를 사용하지 않고도 컴포넌트 내의 요소들에 애니메이션을 적용할 수 있게 해준다. useAnimate 훅은 scope ref와 animate 함수를 반환한다. 

  • const [ scope변수명, animate변수명 ] = useAnimate();
    return <애니메이션 할 요소 ref={scope 변수명} />

  • animate변수명(scope변수명, { 적용할 애니메이션 } )
import { useAnimate } from "framer-motion";

export default function Example() {
    // 각각의 다른 animate 설정
    const [scope1, animate1] = useAnimate();
    const [scope2, animate2] = useAnimate();

    const handleClick = () => {
        // ref를 통해 scope1에 해당하는 div는 animate1의 애니메이션 효과를 주고 
        animate1(scope1.current, { x: 100, opacity: 0.5 });
        // scope2에 해당하는 div는 animate2의 애니메이션 효과를 준다.
        animate2(scope2.current, { background: "blue", x: 200, border: "1px solid black" });
    };

    return (
        <div>
            <div ref={scope1} style={{ width: 100, height: 100, background: "blue" }} />
            <div ref={scope2} style={{ width: 100, height: 100, background: "green" }} />
            <button onClick={handleClick}>Animate</button>
        </div>
    );
}