-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #99 from JohnsonMao/feature/use-request-animation-…
…frame-state - ✨ add request animation frame state hook - ⚡️ optimization scroll event with RAF
- Loading branch information
Showing
3 changed files
with
40 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
import { useCallback, useEffect, useRef, useState } from 'react'; | ||
|
||
/** | ||
* This hook for managing state with RAF (requestAnimationFrame) optimization. | ||
*/ | ||
const useRafState = <S>(initialState: S | (() => S)) => { | ||
const frame = useRef(0); | ||
const [state, setState] = useState(initialState); | ||
|
||
const setRafState = useCallback((value: S | ((prevState: S) => S)) => { | ||
cancelAnimationFrame(frame.current); | ||
|
||
frame.current = requestAnimationFrame(() => { | ||
setState(value); | ||
}); | ||
}, []); | ||
|
||
useEffect(() => { | ||
return () => cancelAnimationFrame(frame.current); | ||
}, []) | ||
|
||
return [state, setRafState] as const; | ||
}; | ||
|
||
export default useRafState; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters