Skip to content

Instantly share code, notes, and snippets.

@lexeeech
Created November 15, 2021 10:44
Show Gist options
  • Save lexeeech/d9c990f060fc2336da184a22811ee75b to your computer and use it in GitHub Desktop.
Save lexeeech/d9c990f060fc2336da184a22811ee75b to your computer and use it in GitHub Desktop.
import React from "react";
import ReactDOM from "react-dom";
// REF
const useRefHandler = () => {
const ref = React.useRef();
const [ready, setReady] = React.useState(false);
const set = (node) => {
setReady(Boolean(node));
ref.current = node;
};
return { set, get: ref, ready };
};
// EXAMPLE
function App() {
const ref = useRefHandler();
const [loading, setLoading] = React.useState(true);
React.useEffect(() => {
setTimeout(() => setLoading(false), 3000);
}, []);
React.useEffect(() => {
if (ref.ready) {
console.log(ref.get);
}
}, [ref.ready]);
if (loading) {
return "loading..";
}
return <span ref={ref.set} />;
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment