DEV Community

Cover image for useSpriteAnimation() like how Facebook does it using React Hooks
Kenneth Lum
Kenneth Lum

Posted on • Edited on

2 2

useSpriteAnimation() like how Facebook does it using React Hooks

When we post animated images to Facebook, it is displayed as Sprite Animation. We can also try using React Hooks to do it.

The image may look like this:

Sprite image

To do animation, we could write a custom React Hook useBackgroundShift():

function useBackgroundShift(size, xacross, yacross, xymax) {
  const [shift, setShift] = useState({ dx: 0, dy: 0 });

  useEffect(() => {
    let intervalID;

    if (size.width !== null && size.height !== null) {
      intervalID = setInterval(() => {
        setShift(({ dx, dy }) => {
          if (dx + dy * yacross + 1 >= xymax) {
            dx = 0;
            dy = 0;
          } else if (++dx >= xacross) {
            dx = 0;
            if (++dy >= yacross) {
              dy = 0;
            }
          }
          return { dx, dy };
        });
      }, 132);
    }

    return () => intervalID && clearInterval(intervalID);
  }, [size.width, size.height, xacross, yacross, xymax]);

  if (size.width === null || size.height === null) return {};

  return {
    backgroundPosition: `-${(shift.dx * size.width) / xacross}px -${
      (shift.dy * size.height) / yacross
    }px`,
    backgroundRepeat: "no-repeat"
  };
}
Enter fullscreen mode Exit fullscreen mode

I also added the ability to animate from frame 1 to frame N, just to see how it works. It is not yet perfect as I only did it as an experiment. Some might be hard coded numbers for the moment, but that's the basic idea of a custom React Hooks to do Sprite Animation.

Demo: https://codesandbox.io/s/beautiful-leaf-o9hew?file=/src/App.js

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)