1.5 KiB
1.5 KiB
title, tags, author, cover, firstSeen
| title | tags | author | cover | firstSeen |
|---|---|---|---|---|
| React useRequestAnimationFrame hook | hooks,effect | chalarangelo | aerial-view-port | 2021-12-29T05:00:00-04:00 |
Runs an animating function, calling it before every repaint.
- Use the
useRef()hook to create two variables.requestRefwill hold the last request id andpreviousTimeRefwill hold the last timestamp. - Define a function,
animate, which handles updating these variables, runs thecallbackand callsWindow.requestAnimationFrame()perpetually. - Use the
useEffect()hook with an empty array to initialize the value ofrequestRefusingWindow.requestAnimationFrame(). Use the returned value andWindow.cancelAnimationFrame()to clean up when the component unmounts.
const useRequestAnimationFrame = callback => {
const requestRef = React.useRef();
const previousTimeRef = React.useRef();
const animate = time => {
if (previousTimeRef.current) callback(time - previousTimeRef.current);
previousTimeRef.current = time;
requestRef.current = requestAnimationFrame(animate);
};
React.useEffect(() => {
requestRef.current = requestAnimationFrame(animate);
return () => cancelAnimationFrame(requestRef.current);
}, []);
};
const Counter = () => {
const [count, setCount] = React.useState(0);
useRequestAnimationFrame(deltaTime => {
setCount(prevCount => (prevCount + deltaTime * 0.01) % 100);
});
return <p>{Math.round(count)}</p>;
};
ReactDOM.createRoot(document.getElementById('root')).render(
<Counter />
);