Skip to content

Instantly share code, notes, and snippets.

@OliverJAsh
Created April 17, 2025 13:59
Show Gist options
  • Save OliverJAsh/9475055d2dc4769696d97f5401a0407f to your computer and use it in GitHub Desktop.
Save OliverJAsh/9475055d2dc4769696d97f5401a0407f to your computer and use it in GitHub Desktop.
const Freeze: FC<{ freeze: boolean; children: ReactNode }> = ({
freeze,
children,
}) => {
const outerRef = useRef<HTMLDivElement>(null);
const ref = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
if (freeze) {
outerRef.current!.appendChild(ref.current!);
}
}, [freeze]);
return freeze ? (
<div ref={outerRef} />
) : (
// Key is needed to ensure React hydrates again.
<div key="defrosted" ref={outerRef}>
<div
ref={(el) => {
// Don't clear when it's removed, otherwise it will be gone before the
// effect.
if (el !== null) {
ref.current = el;
}
}}
>
{children}
</div>
</div>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment