Framer Motion Spring 을 state 로 연결하기

1 minute read
2024-07-26

Framer motion 에서는 스프링처럼 값을 연속적으로 변경하도록 해주는 hook 이 있다. useSpring 훅을 이용해서 자연스러운 애니메이션에 적용 가능하다.


useSpring motionValue 선언하기

useSpring declartion with options
import { useSpring } from 'framer-motion'
 
const [count, setCount] = useState(INITIAL_VALUE);
const motionValue = useSpring(INITIAL_VALUE, {
  // 높을수록 `빠르게` 변경 ( 0 ~ 1_000 )
  stiffness: 500,
  // 높을수록 `빠르게` 멈춤 ( 0 ~ 100 )
  damping: 50,
  // 높을수록 `무겁게` ( 1<= )
  mass: 1.5,
});


이제 이 값의 목표치 값을 변경해줘야 한다. 그렇게 되면, 그 과정에서 변화 양상이 마치 스프링처럼 자연스럽게 변경된다.


set motion value
useEffect(() => {
  motionValue.set(TARGET_VALUE);
}, [motionValue]);


하지만 motionValue 를 바꿨다고 화면에 반영되지 않는다. 화면에 변경을 알리기 위해 상태변경함수를 호출해줘야한다.


상태 변경

update state
motionValue.on('change', (latest: number) => {
  setCount(Math.floor(latest));
});


처음 사용할 때는 motionValue 를 그냥 그대로 value 로 사용해야하는지 알고 있었다. motion 하위 컴포넌트의 style, transition, initial, animate 같은 props 에 사용되지만, state 용도와는 완전 다르다.


그래서 화면에 노출되는 담당은 state 에 맡기고 애니메이션의 변경 흐름은 motionValue 에 맡기는 게, 좋은 사용 방식으로 보인다.


#framer-motion
#react