Skip to content

Instantly share code, notes, and snippets.

@developit
Last active July 25, 2023 12:54
Show Gist options
  • Save developit/2cf32acf60a6efce49006963255ed96a to your computer and use it in GitHub Desktop.
Save developit/2cf32acf60a6efce49006963255ed96a to your computer and use it in GitHub Desktop.
import { h, hydrate, Component } from 'preact';
function interopDefault(mod) {
return mod && mod.default || mod;
}
export function ServerHydrator({ load, ...props }) {
const Child = interopDefault(load());
return (
<section>
<Child {...props} />
</section>
);
}
const EMPTY_HTML = { __html: '' };
export class Hydrator extends Component {
shouldComponentUpdate() {
return false;
}
componentDidMount() {
new IntersectionObserver(async ([entry], obs) => {
if (!entry.isIntersecting) return;
obs.unobserve(this.root);
const { load, ...props } = this.props;
const Child = interopDefault(await load());
hydrate(
<Provider context={this.context}>
<Child {...props} />
</Provider>,
this.root
);
}).observe(this.root);
}
render() {
return (
<section
ref={c => this.root = c}
dangerouslySetInnerHTML={EMPTY_HTML}
/>
);
}
}
class Provider extends Component {
getChildContext() {
return this.props.context;
}
render() {
return this.props.children;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment