Saturday 14 January 2023

Life Cycle Hooks in LWC #salesforce

Lifecycle Hooks A lifecycle hook is a callback method triggered at a specific phase of a component instance’s lifecycle.


There are five types of callback functions :
  1. Constructor()
  2. connectedCallback()
  3. disconnectedCallback()
  4. render()
  5. renderCallback()

constructor()
  1. Called when the component is created.
  2. This hook flows from parent to child, which means that it fires in the parent first. 
  3. You can’t access child elements because they don’t exist yet. Properties aren’t passed yet, either. Properties are assigned to the component after construction and before the connectedCallback() hook.

connectedCallback()

  1. Called when the element is inserted into a dom.
  2. This hook flows from parent to child.
  3. You can’t access child elements because they don’t exist yet.

The connectedCallback() hook can fire more than one time. For example, if you remove an element and then insert it into another position, such as when you reorder a list, the hook fires several times. If you want code to run one time, write code to prevent it from running twice.


The connectedCallback() hook is invoked with the initial properties passed to the component.


renderCallback()

  1. Called after every render of the component.
  2. This lifecycle hook is specific to Lightning Web Components, it isn’t from the HTML custom elements specification.
  3. This hook flows from child to parent.

render()
  1. Call this method to update the UI.
  2. It may be called before or after connectedCallback().
  3. It’s rare to call render() in a component. The main use case is to conditionally render a template. 


disconnectedCallback()
  1. Called when the element is removed from a document.
  2. This hook flows from parent to child.
  3. Use disconnectedCallback() to clean up work done in the connectedCallback(), like purging caches or removing event listeners.

errorCallback()

  1. Called when a descendant component throws an error.
  2. The error argument is a JavaScript native error object, and the stack argument is a string.
  3. This lifecycle hook is specific to Lightning Web Components, it isn’t from the HTML custom elements specification.


Thank you!