javascriptstatestenciljs

When to use a mutable Prop decorator vs when to use a State decorator


I am aware that a prop can be passed into a component where as a state must be set by the component but I'm confused when I should be using a mutable prop vs state.

The docs note:

It is considered a 'best practice' to only use @State() when absolutely necessary.

This implies to me that I should almost always be maintaining the "state" of my components within mutable props, is that correct? If not, what is the correct way to be thinking about the usage of mutable props?

@Component({ tag: 'my-checkbox' })
export class MyCheckbox {
  // Which of these is best?
  @Prop({mutable: true}) checked: string;
  @State() isChecked: string;

  //logic here to update prop or state when input is interacted with

  render() {
    <Host>
      // Which of these is best?
      <input type="checkbox" checked={this.checked} />
      <input type="checkbox" checked={this.isChecked} />
    </Host>
  }
}

Solution

  • Props are part of the public API of the custom element, and therefore can be set via DOM/markup. You should only use a Prop - mutable or not - when you are implementing a public feature. Otherwise use State or internal variables.

    The "absolutely necessary" directive needs to be kept in its context in order to understand it fully - here's the full quote:

    @State() should be used for all class members that should trigger a rerender when they change. However, not all internal state might need to be decorated with @State(). If you know for sure that the value will either not change or that it does not need to trigger a re-rendering, @State() is not necessary. It is considered a 'best practice' to only use @State() when absolutely necessary.

    It is a reference to the topic of internal state in general, not to Prop vs. State. The implication is to use internal variables not State for all component state - unless you need to trigger a rerender when something is changed.