Page Menu
Home
c4science
Search
Configure Global Search
Log In
Files
F99458913
useAnimationFrame.js
No One
Temporary
Actions
Download File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Subscribers
None
File Metadata
Details
File Info
Storage
Attached
Created
Fri, Jan 24, 18:28
Size
1 KB
Mime Type
text/x-java
Expires
Sun, Jan 26, 18:28 (2 d)
Engine
blob
Format
Raw Data
Handle
23788451
Attached To
rOACCT Open Access Compliance Check Tool (OACCT)
useAnimationFrame.js
View Options
import { useRef } from 'react';
import useMounted from './useMounted';
import useStableMemo from './useStableMemo';
import useWillUnmount from './useWillUnmount';
/**
* Returns a controller object for requesting and cancelling an animation freame that is properly cleaned up
* once the component unmounts. New requests cancel and replace existing ones.
*
* ```ts
* const [style, setStyle] = useState({});
* const animationFrame = useAnimationFrame();
*
* const handleMouseMove = (e) => {
* animationFrame.request(() => {
* setStyle({ top: e.clientY, left: e.clientY })
* })
* }
*
* const handleMouseUp = () => {
* animationFrame.cancel()
* }
*
* return (
* <div onMouseUp={handleMouseUp} onMouseMove={handleMouseMove}>
* <Ball style={style} />
* </div>
* )
* ```
*/
export default function useAnimationFrame() {
var isMounted = useMounted();
var handle = useRef();
var cancel = function cancel() {
if (handle.current != null) {
cancelAnimationFrame(handle.current);
}
};
useWillUnmount(cancel);
return useStableMemo(function () {
return {
request: function request(cancelPrevious, fn) {
if (!isMounted()) return;
if (cancelPrevious) cancel();
handle.current = requestAnimationFrame(fn || cancelPrevious);
},
cancel: cancel
};
}, []);
}
Event Timeline
Log In to Comment