1

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?

kraftwer1
  • 5,253
  • 10
  • 36
  • 54

2 Answers2

2

As stated on stencil change @Prop() detection, @Watch decorator of a property triggers when the property value changes, but not when the property is initially set.

To capture the initialization you have to trigger the handler on componentWillLoad passing the property value.

@Watch('name') 
onNameChanged(newValue: string, oldValue: string) {
  this._name = newValue;
}

componentWillLoad(){
  this.onNameChanged(this.name);
}
0

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)

Simon Hänisch
  • 4,740
  • 2
  • 30
  • 42
  • Yes, turned out that @Watch purely operates on the component's JS object `myComp` and is not bound to Stencil's intrinsics in any way. – kraftwer1 Jan 30 '23 at 13:13