matthewp / haunted

React's Hooks API implemented for web components 👻
BSD 2-Clause "Simplified" License
2.59k stars 92 forks source link

Stencil Support #125

Open jdnichollsc opened 5 years ago

jdnichollsc commented 5 years ago

It would be awesome, thanks!

matthewp commented 5 years ago

I'm not super familiar with Stencil, would the work in #123 make this possible?

alfredosalzillo commented 5 years ago

Hi @jdnichollsc,

Why do you need to use hooks inside Stencil components? Stencil manage the state itself. I don't think it's a good idea to mix 'angular style state' with hooks.

edsilv commented 4 years ago

I think the argument for supporting hooks in Stencil is largely one of code reuse/interoperability.

loganvolkers commented 3 years ago

Here's an example component that works. Maybe the boilerplate can be trimmed down and made into a library using some tricks from stencil-store or stencil-wormhole.

import { Component, h, getElement } from '@stencil/core';
import { useState, State } from 'haunted';

@Component({
  tag: 'stencil-hook',
})
export class StencilHook {

  state = new State(() => {
    console.log("Render");
    getElement(this).forceUpdate();
  }, getElement(this));

  render() {
    return this.state.run(() => {
      const [count, setCount] = useState(0);
      return (
        <div>
          Count is {count}
          <button onClick={()=>setCount(count+1)}>+1</button>
        </div>
      );
    });
  }
}
loganvolkers commented 3 years ago

Implemented a possible solution here: https://github.com/ionic-team/stencil/issues/1873#issuecomment-695057903

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>;
  });
}

Source: https://gist.github.com/loganvolkers/6ba4335d0835d69a77b0b37b89589513

loganvolkers commented 3 years ago

Hi @jdnichollsc,

Why do you need to use hooks inside Stencil components? Stencil manage the state itself. I don't think it's a good idea to mix 'angular style state' with hooks.

@alfredosalzillo there are a number of examples of core stencil libraries that support externalizing state, such as stencil-store and stencil-redux -- those were the inspiration for how to wire this in