Search code examples
javascriptreactjsrequestanimationframe

requestAnimationFrame doesn't update repeatedly a react component


Just want to know why my requestAnimationFrame doesn't update my react component repeatedly? it only returned count value the very first time,and then it ignore it. here's the code :

// ----- animation.js
import React from "react";

let count = 0;
export default function Update() {
  return <>{UpdateComponents()}</>;
}

function UpdateComponents() {
  count++;

  window.requestAnimationFrame(UpdateComponents);

  return <p>count: {count}</p>;
}

// ------ index.js
// ReactDOM.render(<Update />, document.getElementById("root"));

Solution

  • requestAnimationFrame is working as you expect, if you add a console.log(count) after the place where you increment count you'll see the value changing.

    The reason it isn't showing up in your DOM is that no component is tracking the value of count so nothing knows that it should be re-rendered. You'll need to hook your updates into state or prop changes in order to make the component show the 'live' count.