日本語

Animating Elements with the Web Animations API in React

​​React​Playwright,StrictMode,TypeScript,useLayoutEffect,useRef,Web Animations API

With the Web Animations API, you can animate an element just by calling animate() on it, without adding or removing CSS classes. In React, you get the element through a ref and call animate() in a click handler or an effect.

Here I built three animations: shaking an element on click, fading it in when it is shown, and fading it out before it is removed. The third animation needs the faded state to stay in place, so before it, I check how to keep the final position (fill: 'forwards' and commitStyles()). In each section, I count what happens in the browser when the code is written differently, and compare the results.

Note

The test environment was Ubuntu 24.04, Node.js 22.22.0, and Chrome for Testing 153. I used react / react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, esbuild 0.28.2, and Playwright 1.56.1. I type-checked the .tsx files with tsc, converted them with esbuild, and ran them in the browser operated by Playwright. Only the StrictMode check used the development build; everything else used the production build. I did not test Firefox or Safari.

Shaking an element on click

When the submit button is pressed, the input box shakes left and right. I get the element to animate with useRef, and call animate() in the click handler.

tsx
import { useRef } from 'react';
import { prefersReducedMotion } from './motion';

const shake: Keyframe[] = [
  { transform: 'translateX(0)' },
  { transform: 'translateX(-8px)' },
  { transform: 'translateX(8px)' },
  { transform: 'translateX(-8px)' },
  { transform: 'translateX(0)' },
];

export function ShakeBox() {
  const boxRef = useRef<HTMLDivElement>(null);
  const animationRef = useRef<Animation | null>(null);

  function handleClick() {
    if (prefersReducedMotion()) return;
    // If a previous shake is still running, cancel it before starting over
    animationRef.current?.cancel();
    animationRef.current =
      boxRef.current?.animate(shake, { duration: 400, easing: 'ease-in-out' }) ?? null;
  }

  return (
    <>
      <div ref={boxRef} className="box">入力してください</div>
      <button onClick={handleClick}>送信</button>
    </>
  );
}

As described on MDN's animate() page, the first argument of animate() is an array of keyframes, and the second is options such as the duration (in milliseconds) and easing. The animation starts playing as soon as it is called. The returned Animation lets you stop it or wait for it to finish. prefersReducedMotion() is a function that checks the reduced-motion setting; it appears later in this article.

I pressed the button once and checked the number of getAnimations() on the box and its transform.

text
押した直後: {"running":1,"created":1,"transform":"matrix(1, 0, 0, 1, 0, 0)","styleAttr":null}
100ms後: {"running":1,"created":1,"transform":"matrix(1, 0, 0, 1, -5.66805, 0)","styleAttr":null}
600ms後: {"running":0,"created":1,"transform":"none","styleAttr":null}

running is the number of animations attached to the box, and created is the number of animations created with animate() so far. 100ms later, the box had moved about 5.7px to the left. At 600ms, after the 400ms shake had finished, the animation had been removed from the element and transform was back to none. Nothing was written to the style attribute. Because animate() does not rewrite the attributes of DOM elements that React rendered, it does not conflict with React's rendering.

Pressing the submit button twice shakes the box each time, and pressing close fades the notice out and removes it
Pressing submit twice shakes the box, and pressing close removes the notice. This is a verification screen with a status display added, captured frame by frame with the animations paused. The button labels in the image are in Japanese: the submit button and the close button.

Stopping the previous shake when clicked repeatedly

Each call to animate() creates a new Animation. If the button is pressed again before the previous shake finishes, multiple animations overlap on the same element. I pressed the button three times at 100ms intervals and compared the state 100ms after the third press. The first line is the version that does not stop the previous shake, and the second line is ShakeBox above.

text
shake-nocancel 3回目の100ms後: {"running":3,"playStates":"running,running,running","transform":"matrix(1, 0, 0, 1, -2.84667, 0)"}
shake 3回目の100ms後: {"running":1,"playStates":"idle,idle,running","transform":"matrix(1, 0, 0, 1, -2.84112, 0)"}

Without stopping, all three shakes were running at the same time. Even so, the box's position (the fifth value in transform) was almost the same as in the version where only the last shake was running. The visible change is small, but the unfinished shakes keep running in the background.

In ShakeBox, the created Animation is stored in a ref, and it is stopped with cancel() the next time the button is pressed. The stopped shakes became idle, and only the last one remained attached to the element. The reason to keep it in a ref is that the Animation is not a value used for display. As described in the useRef reference, changing the contents of a ref does not trigger a re-render.

Fading in when shown

When the panel is shown, it appears while moving down slightly from above. It moves only once, right after it is shown, so I call animate() in an effect and call cancel() in the cleanup.

tsx
import { useLayoutEffect, useRef } from 'react';
import { prefersReducedMotion } from './motion';

const enter: Keyframe[] = [
  { opacity: 0, transform: 'translateY(-12px)' },
  { opacity: 1, transform: 'translateY(0)' },
];

export function Panel() {
  const panelRef = useRef<HTMLDivElement>(null);

  useLayoutEffect(() => {
    if (prefersReducedMotion()) return;
    const animation = panelRef.current?.animate(enter, { duration: 300, easing: 'ease-out' });
    return () => animation?.cancel();
  }, []);

  return <div ref={panelRef} className="panel">保存しました</div>;
}

With useEffect, the starting frame may briefly be visible

I used useLayoutEffect instead of useEffect to prevent flicker. On the first frame after the panel was added to the DOM, I checked its opacity and the number of animations with requestAnimationFrame. I tried 50 times each for two cases: showing the panel after a button click, and showing it inside a setTimeout.

text
panel-effect クリック {"opacity=0 running=1":50}
panel-effect setTimeout {"opacity=1 running=0":8,"opacity=0 running=1":42}
panel クリック {"opacity=0 running=1":50}
panel setTimeout {"opacity=0 running=1":50}

panel-effect is the version that starts the animation in useEffect, and panel is the useLayoutEffect version above. In the useEffect version, when the panel was shown from setTimeout, in 8 of the 50 runs the animation had not yet started on the first frame, and the panel was painted with opacity 1. A panel that should start transparent was briefly fully visible, then disappeared and appeared again. With useLayoutEffect, all 50 runs were already moving from the first frame.

This difference follows the caveat in the useEffect reference. For updates started by an interaction such as a click, an effect may run before the browser paints the screen. For other updates, React usually lets the browser paint first and then runs the effect. useLayoutEffect always runs before the browser repaints. If you add animation to a component that is shown for a reason other than a click, such as after data fetching finishes, useLayoutEffect is the safer choice.

In StrictMode, it is created twice and stopped once

In StrictMode, during development only, the effect's setup and cleanup run one extra time. I ran the development build in StrictMode and checked the state right after the panel was shown. The first line is the Panel above, and the second line is the version without cancel() in the cleanup.

text
panel 出した直後: {"running":1,"created":2,"playStates":"idle,running"}
panel-nocleanup 出した直後: {"running":2,"created":2,"playStates":"running,running"}

In both versions, animate() was called twice. In the version with a cleanup, the first animation was stopped and became idle, so only one was running. In the version without a cleanup, both were running at once. Since the same motion just overlaps, the difference is hard to notice visually. As noted in the useLayoutEffect reference, the cleanup function is also called before the component is removed from the DOM. So if the panel is removed while it is still animating, cancel() is called too.

Keeping the final position

When an animation from animate() ends, the element returns to its original style. The next section needs the notice to stay in its faded state, so I check how to keep the final position here. To move a box 200px to the right and keep it there, either add fill: 'forwards', or write the final value into the style attribute with commitStyles(). The code below uses both: newer browsers can write the value with commitStyles() even without fill, but older browsers need fill. An animation kept by fill is removed with cancel() after its value has been written. I compared the state after the animation ends for three ways of writing the code.

tsx
const animation = box.animate(
  [{ transform: 'translateX(0)' }, { transform: 'translateX(200px)' }],
  { duration: 300, easing: 'ease-out', fill: 'forwards' },
);
await animation.finished;
// Write the final state to the style attribute, then clean up the animation
animation.commitStyles();
animation.cancel();
text
move-none {"running":0,"transform":"none","styleAttr":null}
move-fill {"running":1,"transform":"matrix(1, 0, 0, 1, 200, 0)","styleAttr":null}
move-commit {"running":0,"transform":"matrix(1, 0, 0, 1, 200, 0)","styleAttr":"transform: translateX(200px);"}

The first line is the version with neither fill nor commitStyles(), and the box returned to its original position. The second line is the version with only fill: 'forwards'. The box stays at 200px, but the finished animation remains attached to the element. The third line is the code above: transform: translateX(200px); was written to the style attribute, and the animation was removed.

The reason not to rely on fill: 'forwards' alone is explained on MDN's commitStyles() page. Animation values take precedence over normal styles. If the animation stays attached, then even if you change the class or style later, the transform of that element will not change.

Warning

commitStyles() rewrites the style attribute of an element that React rendered, bypassing React. React's documentation on manipulating the DOM with refs recommends limiting changes to React-managed DOM to parts that React has no reason to update. Only commit properties that you do not specify in the style prop.

When I ran a shake with fill: 'forwards' three times at 500ms intervals, only the last animation remained attached to the element. The replaceState of the two earlier ones is removed.

text
shake-fill 終わったあと: {"running":1,"replaceStates":"removed,removed,active"}

As described on MDN's Web Animations API usage page, a finished animation with fill is removed automatically by the browser when a new animation that changes the same properties overrides it. If you only repeat the same motion, finished animations do not keep accumulating.

Fading out before removal

When the close button on the notice is pressed, the notice fades out while shifting to the right, and then it is removed from the DOM. If you remove the element by changing React state, it leaves the DOM immediately. So I first animate it with animate(), wait for the finished promise, and only then change the state.

tsx
import { useRef, useState } from 'react';
import { prefersReducedMotion } from './motion';

const exit: Keyframe[] = [
  { opacity: 1, transform: 'translateX(0)' },
  { opacity: 0, transform: 'translateX(24px)' },
];

function Notice({ onClose }: { onClose: () => void }) {
  const noticeRef = useRef<HTMLDivElement>(null);
  const closingRef = useRef(false);

  async function handleClose() {
    const notice = noticeRef.current;
    if (!notice || closingRef.current) return;
    closingRef.current = true;
    if (!prefersReducedMotion()) {
      // Keep fill: 'forwards' so the element stays in its faded state
      const animation = notice.animate(exit, { duration: 250, easing: 'ease-in', fill: 'forwards' });
      await animation.finished;
    }
    onClose();
  }

  return (
    <div ref={noticeRef} className="notice">
      保存しました
      <button onClick={handleClose}>閉じる</button>
    </div>
  );
}

export function NoticeArea() {
  const [open, setOpen] = useState(true);
  return (
    <>
      <button onClick={() => setOpen(true)}>通知を出す</button>
      {open && <Notice onClose={() => setOpen(false)} />}
    </>
  );
}

closingRef is set to true when the closing animation starts. If the close button is pressed again while the notice is fading, the handler returns without doing anything, because the flag is already true. That way, the animation is not created twice. When I pressed the button twice in a row, only one animation was created, and the notice had been removed from the DOM 500ms later.

text
2回押した直後: 作られたアニメーション 1
500ms後: 通知 0 個

Without fill, it briefly returns to its original look just before disappearing

fill: 'forwards' is here to prevent the original appearance from showing for a moment between the end of the animation and the removal from the DOM. After pressing close, I recorded the opacity on every frame until the notice disappeared. The first line is the version without fill, and the second line is the code above.

text
notice-nofill 1回目の記録: 1.00 1.00 1.00 1.00 0.99 0.97 0.94 0.90 0.84 0.79 0.72 0.65 0.57 0.49 0.40 0.31 0.21 0.11 1.00 なし
notice 1回目の記録: 1.00 1.00 1.00 1.00 1.00 0.99 0.97 0.94 0.89 0.84 0.78 0.72 0.65 0.57 0.49 0.40 0.31 0.21 0.11 0.00 0.00 なし

In the first recording of the version without fill, the opacity dropped to 0.11, then returned to 1.00 on the next frame, and on the frame after that the notice was removed from the DOM. Out of 20 runs, all 20 returned to 1.00 before disappearing. When the animation ends, the element goes back to its original style, and it seems that one frame was painted before React rewrote the DOM after finished resolved. In the version with fill: 'forwards', none of the 20 runs returned to 1.00. This element is removed from the DOM right away, so keeping fill does not cause the problem that fill alone would cause.

If cancel() is called midway, the finished promise is rejected with an AbortError (MDN's cancel() page). In this notice, there is no case where the closing animation is stopped, so this article does not handle the rejection. If you design it so the animation can be stopped midway, wrap the await in a try block.

Respecting the reduced-motion setting

For people who have turned on the reduce-motion setting in their OS, no animation is played. You can check the same condition as the CSS prefers-reduced-motion media feature from JavaScript with matchMedia(). All three components above check this function before they animate.

ts
// true if reduced motion is enabled
export function prefersReducedMotion() {
  return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
}

I opened the page in Playwright with reducedMotion: 'reduce', then pressed the submit button and the close button.

text
matchMedia: true
shake 押した直後: {"running":0,"created":0}
notice 閉じた直後: 0 個 / 作られたアニメーション 0

No animations were created, and the notice disappeared right after the close button was pressed.

​Posted by 86