2

As opposed to what is mentioned in Spring's documentation, useSpring does not animate my counter component on prop change:

If you re-render the component with changed props, the animation will update.

I've tried passing the props as children, to no effect. What am I missing? Here's a demo: https://codesandbox.io/s/spring-counter-jsylq?file=/src/App.js:199-230

import React, { useState } from "react";
import { animated, useSpring } from "react-spring";

const Counter = ({ value }) => {
  const anim = useSpring({ from: { opacity: 0 }, to: { opacity: 1 } });

  return <animated.h1 style={anim}>{value}</animated.h1>;
};

export default function App() {
  const [count, setCount] = useState(0);

  return (
    <>
      <Counter value={count} />
      <button onClick={() => setCount(count + 1)}>increment</button>
    </>
  );
}
msalla
  • 717
  • 6
  • 23

1 Answers1

4

It only said the animation will update. But now the animation is kind of static.

You can do a couple of things. If you add the reset property then it will repeat the initial animation at every re-render.

const anim = useSpring({ from: { opacity: 0 }, to: { opacity: 1 } , reset: true});

Or you can add some properties depending of the count value. For example the parity. Odd became blue, even number to red.

const anim = useSpring({ from: { opacity: 0 }, to: { opacity: 1 , color: value % 2 === 0 ? 'red' : 'blue'} });

What do you think?

https://codesandbox.io/s/spring-counter-forked-znnqk

Peter Ambruzs
  • 7,763
  • 3
  • 30
  • 36