Tuesday, December 20, 2022

LWC RenderedCallback

Run Code When a Component Renders

The renderedCallback() is unique to Lightning Web Components. Use it to perform logic after a component has finished the rendering phase.

This hook flows from child to parent.

When a component renders, the expressions used in the template are reevaluated.

After a component is connected and rendered, a change (or mutation) to the component’s state marks the component as dirty and enqueues a microtask to rerender the component. For more information about which changes are tracked, see Reactivity.

A component is usually rendered many times during the lifespan of an application. To use this hook to perform a one-time operation, use a boolean field like hasRendered to track whether renderedCallback() has been executed. The first time renderedCallback() executes, perform the one-time operation and set hasRendered = true. If hasRendered = true, don’t perform the operation.

It’s best to add event listeners declaratively in an HTML template. However, if you do need to add an event listener to a template element programmatically, do it in renderedCallback(). You don’t need to remove the listener. If a listener is added to the same element repeatedly, the browser ignores the duplicates.

When a template is rerendered, the LWC engine attempts to reuse the existing elements. In the following cases, the engine uses a diffing algorithm to decide whether to discard an element.

  • Elements created using the for:each directive. The decision to reuse these iteration elements depends on the key attribute. If key changes, the element may be rerendered. If key doesn’t change, the element isn’t rerendered, because the engine assumes that the iteration element didn’t change.
  • Elements received as slot content. The engine attempts to reuse an element in a <slot>, but the diffing algorithm determines whether to evict an element and recreate it.

Updating the state of your component in renderedCallback() can cause an infinite loop. For example:

  • Don’t update a wire adapter configuration object property in renderedCallback(). See Understand the Wire Service.
  • Don’t update a public property or field in renderedCallback(). See Reactivity.
Example The libsChartjs module in the lwc-recipes samples repo uses the renderedCallback() lifecycle hook.

No comments:

Post a Comment