Rooks
Animation & Timing

useSpring

A hook that animates a value using spring physics.

useSpring

useSpring is a hook that animates a value using spring physics. It simulates a spring force to move a value towards a target.

Usage

import { useSpring } from "rooks";
 
function App() {
  const [target, setTarget] = useState(0);
  const value = useSpring(target, {
      stiffness: 170,
      damping: 26,
      mass: 1
  });
 
  return (
    <div>
        <button onClick={() => setTarget(target === 0 ? 100 : 0)}>
            Toggle
        </button>
        <div style={{ transform: `translateX(${value}px)` }}>
            Moving Box
        </div>
    </div>
  );
}

Arguments

ArgumentTypeDefaultDescription
targetValuenumber-The value to animate towards.
configSpringConfigConfiguration object for the spring.

SpringConfig

PropertyTypeDefaultDescription
stiffnessnumber170Spring stiffness. Higher values create a snappier spring.
dampingnumber26Spring damping. Higher values reduce oscillation.
massnumber1Mass of the object attached to the spring.
precisionnumber0.01Precision threshold to stop the animation.

Return Value

Returns the current animated value.

On this page