Search code examples
javascriptreactjsframer-motion

Framer Motion - stale custom value - changing the custom value doesn't trigger an update


Using framer-motion, I have an issue where updating the object I pass on the custom prop to the motion.div variants doesn't trigger the expected style change.

I created the following sandbox in order to demonstrate the issue:

https://codesandbox.io/s/framer-motion-stale-custom-fibp5?file=/src/App.js

My expectation is that when I toggle the theme - the circle's on/off colors will immediately change based on the new theme. (from black/white to darkblue/yellow and vice versa).

However, the theme changes are applied only once the animation value is changed (status changes from "on" to "off" etc.) So when I toggle the theme, I'm showing a "stale" theme value until I also toggle the status (on/off).

Any help would be greatly appreciated.


Solution

  • Yes, seems quite unexpected, maybe that's a bug.

    Not sure that this will work for your use case, but what you can do right now is to use React key prop to force motion.div re render after theme change. Like that:

          <motion.div
            key={theme}
            style={styles.circle}
            variants={VARIANTS}
            animate={status}
            initial={false}
            custom={theme}
          />
    

    Note that I also set initial={false} because otherwise animation will start at off state event if you are really at on.

    Codesandbox: https://codesandbox.io/s/httpsstackoverflowcomquestions64027738-cwj9k?file=/src/App.js