Andy Desmarais

A code ninja and all around tech geek

StencilJs - Part 5 - @State Decorator

2019-12-20 Andy DesmaraisWebComponents

Cover photo credit: Alfred Schrock

This article assumes you have a working knowledge of web components. If you don’t, please check out my earlier series on web components.

It’s also building on a previous article, so please check that out too.

Component State

Many times when writing components we need to store some stateful information that’s only relevant to that component. Stencil handles this with the @State decorator for properties.

The key concept with @State is that it should only be used on properties that will require a re-render if they change. You should avoid using this decorator for anything that does not require the render method to be called again.

There are no options for this decorator.

Here’s a quick example:

@Component({
  tag: 'my-custom-element'
})
export class MyCustomElement {
  @State() numberOfClicks: number;

  render() {
    return [
      <div>{this.numberOfClicks}</div>
      <button onClick={() => { this.numberOfClicks++; }}>Plus One</button>
    ];
  }
}