-
Notifications
You must be signed in to change notification settings - Fork 50
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
fa65e33
commit cc4df33
Showing
3 changed files
with
25 additions
and
16 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,13 +1,20 @@ | ||
import React from 'react'; | ||
import { useRef } from 'react'; | ||
|
||
function useFunction<T extends (...args: any[]) => any>(fn: T) { | ||
const ref = React.useRef<Function>(() => { | ||
throw new Error('Cannot call function while rendering.'); | ||
}); | ||
export type noop = (...args: any[]) => any; | ||
|
||
ref.current = fn; | ||
function usePersistFn<T extends noop>(fn: T) { | ||
const fnRef = useRef<T>(fn); | ||
fnRef.current = fn; | ||
|
||
return React.useCallback(ref.current as T, [ref]); | ||
const persistFn = useRef<T>(); | ||
if (!persistFn.current) { | ||
persistFn.current = function (...args) { | ||
// eslint-disable-next-line @typescript-eslint/no-invalid-this | ||
return fnRef.current!.apply(this, args); | ||
} as T; | ||
} | ||
|
||
return persistFn.current!; | ||
} | ||
|
||
export default useFunction; | ||
export default usePersistFn; |
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