Skip to content

Instantly share code, notes, and snippets.

@stryju

stryju/useFPS.js

Created Nov 30, 2019
Embed
What would you like to do?
function useFPS() {
const [fps, setFPS] = useState(0);
useEffect(() => {
let then = performance.now();
let frames = 0;
let req;
(function loop(now) {
req = window.requestAnimationFrame(loop);
frames++;
if (now - then >= 1000) {
setFPS(Math.round((frames * 1000) / (now - then)));
frames = 0;
then = now;
}
})(then);
return () => window.cancelAnimationFrame(req);
}, [setFPS]);
return fps;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment