Last active
July 25, 2023 12:54
-
-
Save developit/2cf32acf60a6efce49006963255ed96a to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { 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