Search code examples
stenciljs

From when is @Watch() active?


I'm trying to understand the @Watch() part of the Stencil lifecycle docs: https://stenciljs.com/docs/component-lifecycle To me, the illustration above does not clearly show from when @Watch() actually starts watching.

There seem to be cases where a @Watch() hook is triggered even before componentWillLoad(), for example when a Stencil component is used in React with React.createRef(). These cases are not always reproducible - meaning that it could be a race condition.

That's why I'd like to know from what particular point in time @Watch() becomes active?


Solution

  • As can be seen in the graphic of your linked doc page, a @Watch() decorated method is called every time a change in the value of prop or state you watch occurs. That is independent from the willLoad/willRender/render/didRender/didLoad/didUpdate cycle that occurs when the component is attached to the DOM.

    @Component({ tag: 'my-comp' })
    export class MyComp {
      @Prop() input = 'foo';
      @State() repeated: string;
    
      @Watch('input')
      onInputChange() {
        this.repeated = this.input + this.input;
      }
    
      componentWillLoad() {
        this.onInputChange(); // can manually call the watcher here
      }
    
      render() {
        return this.repeated;
      }
    }
    
    <script>
      const myComp = document.createElement('my-comp');
    
      // currently `repeated` would be undefined because the component has not yet rendered
    
      myComp.input = 'foobar'; // now `repeated` *should* be `foobarfoobar`
    </script>
    

    (saying *should* because I haven't tested this)