react-spring Documentation

website·Indexed 34 days ago

https://react-spring.dev

A library for building interactive, data-driven, and animatable interfaces in React. Features a variety of hooks and components including useSpring, useTransition, useTrail, useChain, and useSprings, as well as utilities like useScroll, useResize, and useInView. Provides an imperative API via SpringRef and SpringValue, and supports integration with React Three Fiber.

Tokens
17.1K
Snippets
103
Records
116
Agent score
71%

What's inside react-spring

  1. Overview of react-spring animation library

    react-spring is a spring-physics based animation library for React. Unlike libraries that rely on setState to update styles, react-spring bypasses the React render loop for animation updates, allowing for smooth, fluid performance without unnecessary re-renders. It is written in TypeScript and supports Server-Side Rendering (SSR).
  2. Create staggered animations with useTrail

    useTrail is a hook used to orchestrate multiple springs so they trigger one after another in a staggered sequence. It shares an identical API signature to useSprings but handles the timing offset automatically for each element in the trail.
  3. Orchestrate multiple animations with useSprings

    The useSprings hook is used to create and manage multiple spring animations simultaneously. It requires a count of springs to be created and a configuration object or function defining the animation properties.
  4. Understand react-spring targets and available packages

    In react-spring, a 'target' refers to a React reconciler (renderer) that processes JSX components and updates elements on a specific platform. Different targets allow react-spring to work across various rendering environments.

    Available official targets include:

    • web: Uses react-dom
    • native: Uses react-native
    • three: Uses react-three-fiber
    • konva: Uses react-konva
    • zdog: Uses react-zdog
    # Example: Install the web target
    yarn add @react-spring/web
  5. Animate item entry and exit with useTransition

    The useTransition hook is used to animate datasets or individual items (like dialogs) as they are added to or removed from the DOM. It tracks items based on an array of data and manages their transition states (entering, updating, leaving).
  6. Understand the Fluid event system in react-spring

    Fluids are a glue layer for observable events that enable a parent-child event-driven system. In the context of SpringValue, a FluidObserver triggers the _start function when an event is observed, which initiates the animation of the value and subsequently updates the attached animated node. This system is used throughout the library to schedule updates via the rafz package.
  7. Understand the relationship between useSpring, Controllers, and SpringValues

    The useSpring hook is a React wrapper around the Controller class. When useSpring is called, it initializes a Controller instance. The hook returns an array containing two elements: styles and api.

    • styles: An object where each key corresponds to an animatable property defined in the config. The value of each key is a SpringValue instance. These SpringValue objects are passed to animated components to drive animations.
    • api: A SpringRef which acts as an abstraction over the Controller methods, allowing imperative control over one or more controllers.
    const [styles, api] = useSpring(() => ({
      x: 0,
      y: 0,
      backgroundColor: '#ff0000',
      scale: [1, 1, 1],
      config: {
        precision: 0.0001,
      },
    }))
    
    // styles = { x: SpringValue, y: SpringValue, ... }
    // api = SpringRef (Controller abstraction)
  8. Chain animations using an array in the to prop

    To perform a sequence of animations where each step finishes before the next begins, pass an array of objects to the to prop. You only need to specify the keys that change for each step; other values will persist from the previous state.
    import { useSpring, animated } from '@react-spring/web'
    
    export default function MyComponent() {
      const springs = useSpring({
        from: { background: '#ff6d6d', y: -40, x: 0 },
        to: [
          { x: 80, background: '#fff59a' },
          { y: 40, background: '#88DFAB' },
          { x: 0, background: '#569AFF' },
          { y: -40, background: '#ff6d6d' },
        ],
        loop: true,
      })
    
      return (
        <animated.div
          style={{
            width: 40,
            height: 40,
            borderRadius: 4,
            ...springs,
          }}
        />
      )
    }
  9. Create and use an animated value with useSpringValue

    The useSpringValue hook is a wrapper around a SpringValue that allows you to manage an animated value imperatively. It is particularly useful when you need many different springs running in parallel without the overhead of multiple useSpring hooks. The returned value can be passed directly to animated components.
    import { useSpringValue, animated } from '@react-spring/web'
    
    function MyComponent() {
      // Initialize with a starting value of 0
      const opacity = useSpringValue(0)
    
      return <animated.div style={{ opacity }}>Hello World</animated.div>
    }
  10. Test react-spring components by skipping animations

    Because useSpring animates values over time, standard assertions may fail if they run before the animation completes. To make tests deterministic and faster, you can disable animations globally using the Globals.assign method. Even with animations skipped, a tick of the environment is still required for changes to reflect, meaning you must still use waitFor from @testing-library/react or manually advance timers.
    import { render, screen, waitFor } from '@testing-library/react'
    import { animated, useSpring, Globals } from '@react-spring/web'
    import { FadeIn } from './FadeIn'
    
    beforeAll(() => {
      Globals.assign({
        skipAnimation: true,
      })
    })
    
    test('Correctly renders the FadeIn component', async () => {
      const { rerender } = render(<FadeIn>Hello!</FadeIn>)
      const element = screen.getByText('Hello!')
    
      expect(element).toHaveStyle('opacity: 0')
    
      rerender(<FadeIn isVisible>Hello!</FadeIn>)
    
      await waitFor(() => {
        expect(element).toHaveStyle('opacity: 1')
      })
    })
  11. Orchestrate animation sequences with useChain

    useChain is used to run different types of animation hooks (e.g., useSpring and useTransition) in sequence. By default, the next animation in the chain starts after the previous one has come to rest. To use useChain, you must provide a reference to each animation hook using useSpringRef.
    import { useTransition, useSpring, useChain, animated, useSpringRef } from '@react-spring/web'
    
    function MyComponent() {
      const springRef = useSpringRef()
      const springs = useSpring({
        ref: springRef,
        from: { size: '20%' },
        to: { size: '50%' },
      })
    
      const transRef = useSpringRef()
      const transitions = useTransition(['hi', 'there!'], {
        ref: transRef,
        from: { scale: 0 },
        enter: { scale: 1 },
        leave: { scale: 0 },
      })
    
      // Orchestrate: spring runs first, then transition runs after spring rests
      useChain([springRef, transRef])
    
      return (
        <animated.div style={{ height: springs.size, width: springs.size, background: 'blue' }}>
          {transitions((style, item) => (
            <animated.div style={{ width: '120px', height: '120px', background: 'green', ...style }}>
              {item}
            </animated.div>
          ))}
        </animated.div>
      )
    }
  12. Install React Spring for web

    React Spring provides different versions based on your React version. Use the @react-spring/web package for web-based animations.
    # For React >= 19
    yarn add @react-spring/web
    
    # For React < 19
    yarn add @react-spring/web@9