Page Menu
Home
c4science
Search
Configure Global Search
Log In
Files
F100845320
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
Mon, Feb 3, 05:36
Size
1 KB
Mime Type
text/x-java
Expires
Wed, Feb 5, 05:36 (1 d, 21 h)
Engine
blob
Format
Raw Data
Handle
24043801
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