Skip to content

Instantly share code, notes, and snippets.

@loganvolkers
Last active October 19, 2020 22:47
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loganvolkers/6ba4335d0835d69a77b0b37b89589513 to your computer and use it in GitHub Desktop.
Save loganvolkers/6ba4335d0835d69a77b0b37b89589513 to your computer and use it in GitHub Desktop.
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