react-frame-rate
TypeScript icon, indicating that this package has built-in type declarations

2.1.14 • Public • Published

react-frame-rate Coverage Build npm

Create smooth animation in React components with ~60FPS.

Demo

Usage

npm install react-frame-rate --save or yarn add react-frame-rate

◦ React hook useFrameRateManager:

import * as React from "react";

import { useFrameRateManager } from "react-frame-rate";

export function Counter() {
  const [counter, setCounter] = React.useState(0);

  const {
    updateCallback,
    updateFrameRate,
    updateAnimation
  } = useFrameRateManager();

  React.useEffect(() => {
    updateCallback(() => setCounter((value) => value + 1));
  }, [updateCallback, setCounter]);

  React.useEffect(() => {
    updateFrameRate(30);
  }, [updateFrameRate]);

  React.useEffect(() => {
    updateAnimation(true);
    return () => {
      updateAnimation(false);
    };
  }, [updateAnimation]);

  return <div>{counter}</div>;
}

Props:

  • updateCallback - set callback which is called on each frame.
  • updateFrameRate - set desired frame rate value, optimal values 60/30/20/15/10/6/5/3/1.
  • updateAnimation- set start/stop animation with boolean flag.

◦ React HOC withReactFrameRate:

import * as React from "react";

import withReactFrameRate, { BaseUpdateProps } from "react-frame-rate";

type Props = Readonly<{
  counter: number;
}> &
  BaseUpdateProps;

export function Counter() {
  const [isAnimating, setIsAnimation] = React.useState(true);

  const updateState = React.useCallback<(state: Props) => Props>(
    (state: Props) => {
      const newCounter = state.counter + 1;
      if (newCounter >= 100) {
        setIsAnimation(false);
      }
      return { ...state, counter: newCounter };
    },
    [setIsAnimation]
  );

  const options = React.useMemo(
    () => ({
      updateState,
      frameRate: 30
    }),
    [updateState]
  );

  const WithAnimation = React.useMemo(
    () =>
      withReactFrameRate<Props>(options)((props: Props) => (
        <>{props.counter}</>
      )),
    [options]
  );

  return <WithAnimation counter={0} isAnimating={isAnimating} />;
}

Options:

  • updateState - refresh state on each frame.
  • frameRate - current frame rate for updateState. For efficient animation use frameRate - 60/30/20/15/10/6/5/3/1.

◦ Codesandbox

◦ Demo

Contributing

Contributing are Welcome 🎉 Please check out the Contributing guide.

LICENSE

MIT License

Keywords

requestAnimatioFrame react smooth animation

Package Sidebar

Install

npm i react-frame-rate

Weekly Downloads

2

Version

2.1.14

License

MIT

Unpacked Size

16.6 kB

Total Files

12

Last publish

Collaborators

  • stesel23