Skip to content

Instantly share code, notes, and snippets.

@dragonman225
Last active September 1, 2021 08:26
Show Gist options
  • Save dragonman225/184f11237bd42685003223ef1c71c0e1 to your computer and use it in GitHub Desktop.
Save dragonman225/184f11237bd42685003223ef1c71c0e1 to your computer and use it in GitHub Desktop.
React.useRef for functions.
// Copyright (c) 2021 Wen-Zhi (Alexander) Wang <zxcvb22217@gmail.com>
// 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