Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Stencil Hooks
import { Component, h } from '@stencil/core';
import { useState } from 'haunted';
import { useHook } from './stencil-hooks';
@Component({
tag: 'example-hook',
})
export class ExampleHook {
render = useHook(this, () => {
const [count,setCount] = useState(0);
return <div>Child is {count} <button onClick={()=>setCount(count+1}></button></div>;
});
}
import { State } from 'haunted';
import { getElement, JSX } from '@stencil/core';
const StateProp = Symbol("state");
export function useHook(component:unknown, hook:()=>JSX.Element|JSX.Element[]){
let state = component[StateProp];
if(!state){
const element = getElement(component);
state = component[StateProp] = new State(
()=>element.forceUpdate(),
element
)
//@ts-ignore
const {disconnectedCallback} = component;
component["disconnectedCallback"] = function(){
state.teardown();
state = null;
disconnectedCallback && disconnectedCallback();
}
}
return ()=>{
const out = state.run(hook)
state.runEffects();
return out;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment