Skip to content

Instantly share code, notes, and snippets.

@Willmo36
Created April 9, 2020 20:31
Show Gist options
  • Save Willmo36/3dadc5b1457ab573587d3a2f4fa6327e to your computer and use it in GitHub Desktop.
Save Willmo36/3dadc5b1457ab573587d3a2f4fa6327e to your computer and use it in GitHub Desktop.
fp-ts React ref proxy
function refProxy<T>(
ref: React.MutableRefObject<T>
): React.MutableRefObject<T> & { current: O.Option<T> } {
const p = new Proxy(
ref as React.MutableRefObject<T> & { current: O.Option<T> },
{
get: (target, prop) => {
if (prop === "current") {
return O.fromNullable(target.current);
}
return (target as any)[prop];
}
}
);
return p;
}
function useSafeRef<T>() {
return refProxy(React.useRef<T | null>(null));
}
@mishazawa
Copy link

how to assign to ref.current ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment