Last active
November 29, 2019 13:45
-
-
Save fnky/a3f825d13ccd5899a5dc06d8a2f31305 to your computer and use it in GitHub Desktop.
Lazy conditionals and refs
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
function BetterFixedLazyExample({ lazyValue }) { | |
// Initialize with null value. | |
const myRef = useRef(null); | |
useLayoutEffect(() => { | |
console.log(myRef.current); // => HTMLDivElement DOM node | |
}, []); | |
// Make sure the ref setter is not blocked by conditionals. | |
return ( | |
<div ref={myRef}> | |
... | |
</div> | |
) | |
} | |
// Lift the conditional for lazy values up to a parent component. | |
function BetterFixedLazyExampleContainer() { | |
if (lazyValue) { | |
return <div /> | |
} | |
return <BetterFixedLazyExample /> | |
} |
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
function FixedLazyExample({ lazyValue }) { | |
// Initialize with null value. | |
const myRef = useRef(null); | |
useLayoutEffect(() => { | |
console.log(myRef.current); // => HTMLDivElement DOM node | |
}, []); | |
// Make sure the ref setter is not blocked by conditionals. | |
return ( | |
<div ref={myRef}> | |
{ lazyValue ? <div /> : <div />} | |
</div> | |
) | |
} |
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
function LazyExample({ lazyValue }) { | |
// Initialize with null value. | |
const myRef = useRef(null); | |
useLayoutEffect(() => { | |
console.log(myRef.current); // => null | |
}, []); | |
// Initial value of `lazyValue` may be false and true on next update. | |
// This will block the second return from setting the ref, and make the ref unavailable on first render. | |
if (lazyValue) { | |
return <div /> | |
} | |
return <div ref={myRef} /> | |
} |
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
function SyncExample() { | |
// Initialize with null value. | |
const myRef = useRef(null); | |
// Use useLayoutEffect to get the DOM node from a ref passed to a React element. | |
useLayoutEffect(() => { | |
console.log(myRef.current); // => HTMLDivElement DOM node | |
}, []); | |
return <div ref={myRef} /> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment