Data should flow from parent to child in a single direction to reduce code complexity and unintended side effects.

When a component decorates a field with @api to expose it as public property, the value should be set only when the field is initialized. Only the owner component should set the value after the field has been initialized. Values passed to a component should be treated as read-only.

A child component can send an event to the parent to cause a mutation for a property value provided by an owner component. If the parent owns the data, the parent can change the value of the property, which propagates down to the child component via the one-way data binding.

Objects Passed to Components Are Read-Only

A non-primitive value passed to a component (such as an object or array) is read-only. The component cannot modify the object or array’s content. If the component attempts to change the content, an error message appears in the browser console. Make a shallow copy of the objects you want to mutate to mutate the data.

To trigger a mutation for a property value provided by an owner component, a component should send an event to the owner.

Use Primitive Values for Public Properties

Instead of using object data types for properties, the recommendation is to use primitive data types. Slice complex data structures in a higher-level component and pass the primitive values to the component descendants.

There are a few reasons why using primitive values is preferable.

  • Primitive values necessitate specific @api properties that clearly define the data shape. Accepting an object or an array necessitates documentation to specify the shape. If an object’s shape changes, consumers break.
  • For attributes, standard HTML elements only accept primitive values. When a standard HTML element requires a complex shape, it employs the use of child components. A table element, for example, employs the tr and td elements. HTML allows only primitive types to be defined. <table data=…>, for example, is not a value in HTML, but only in Lightning Web Components.

Join 155 other subscribers