Run Code When a Component Renders

The renderedCallback() lifecycle hook 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, any changes or mutations to its state trigger the rerendering process:

  1. The component gets marked as "dirty."
  2. A microtask rerender the component gets enqueued.

For example, components get rerendered when a property's value changes and that property is used either directly in a component template or indirectly in the getter of a property that is used in a template. To learn more about which changes are tracked, see Reactivity.

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.

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.

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.

The libsChartjs module in the lwc-recipes samples repo uses the renderedCallback() lifecycle hook.

See Also