Skip to content

Instantly share code, notes, and snippets.

@fnky
Last active November 29, 2019 13:45
Show Gist options
  • Save fnky/a3f825d13ccd5899a5dc06d8a2f31305 to your computer and use it in GitHub Desktop.
Save fnky/a3f825d13ccd5899a5dc06d8a2f31305 to your computer and use it in GitHub Desktop.
Lazy conditionals and refs
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 />
}
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>
)
}
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} />
}
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