Created
November 15, 2021 10:44
-
-
Save lexeeech/d9c990f060fc2336da184a22811ee75b to your computer and use it in GitHub Desktop.
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
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