Last active
September 1, 2021 08:26
-
-
Save dragonman225/184f11237bd42685003223ef1c71c0e1 to your computer and use it in GitHub Desktop.
React.useRef for functions.
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
// Copyright (c) 2021 Wen-Zhi (Alexander) Wang <[email protected]> | |
// SPDX-License-Identifier: MIT | |
import { useRef } from 'react'; | |
function assert(mayBeFunction) { | |
if (typeof mayBeFunction !== 'function' && mayBeFunction != null) { | |
console.log(mayBeFunction); | |
throw new Error( | |
'It is now allowed to pass in a thing that is not a function, ' + | |
'undefined, or null to useFunctionRef' | |
); | |
} | |
} | |
/** | |
* `React.useRef` for functions. | |
* | |
* If `undefined` or `null` is passed in, `current` returns a dummy | |
* function, so `current` is always callable. | |
* @param {function} initialFunction | |
* @returns | |
*/ | |
export function useFunctionRef(initialFunction) { | |
assert(initialFunction); | |
const r = useRef( | |
(() => { | |
const dummyFn = () => {}; | |
let fn = initialFunction || dummyFn; | |
return { | |
get current() { | |
return fn; | |
}, | |
set current(newFn) { | |
assert(newFn); | |
fn = newFn || dummyFn; | |
}, | |
}; | |
})() | |
); | |
return r.current; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment