Overview
Lifecycle hooks are special callback methods that execute at specific stages of a component’s lifecycle. They allow you to run code when a component is created, added to the DOM, updated, or removed.Lifecycle hooks are reserved method names. Do not create custom methods with these names.
Available Lifecycle Hooks
connectedCallback()
Called when the component is inserted into the DOM. Use this hook to:- Initialize component state
- Fetch initial data
- Register event listeners
- Set up subscriptions
force-app/main/default/lwc/viewToRefresh/viewToRefresh.js:15-20
The
connectedCallback() can fire more than once. For example, if you remove a component from the DOM and then reinsert it, the hook fires again.renderedCallback()
Called after every render of the component. Use this hook to:- Perform DOM manipulations
- Initialize third-party libraries
- Measure element dimensions
- Set focus on elements
force-app/main/default/lwc/libsChartjs/libsChartjs.js:62-77
The
renderedCallback() fires frequently. Always use a guard to ensure expensive operations run only once or when necessary.disconnectedCallback()
Called when the component is removed from the DOM. Use this hook to:- Clean up event listeners
- Cancel pending operations
- Unregister handlers
- Clear timers and intervals
force-app/main/default/lwc/viewToRefresh/viewToRefresh.js:22-24
errorCallback(error, stack)
Called when a descendant component throws an error. Use this hook to:- Handle errors in child components
- Log errors to external services
- Display error messages to users
- Implement error boundaries
The
errorCallback() only catches errors in the component’s descendants, not in the component itself.Lifecycle Flow
The typical lifecycle sequence is:- constructor() - Component instance is created
- connectedCallback() - Component inserted into DOM
- renderedCallback() - Component rendered (fires after every render)
- disconnectedCallback() - Component removed from DOM
Common Patterns
Initialize Once Pattern
Subscription Pattern
Timer Pattern
Best Practices
- Always clean up: Use
disconnectedCallback()to clean up resources created inconnectedCallback() - Guard renderedCallback(): Use flags to prevent running expensive operations on every render
- Don’t manipulate state in renderedCallback(): This can cause infinite render loops
- Use async carefully: Lifecycle hooks can be async, but be cautious about race conditions
- Error boundaries: Implement
errorCallback()in top-level components for better error handling
Restrictions
You cannot access child elements in the
constructor(). Use connectedCallback() or renderedCallback() instead.- Don’t use
this.template.querySelector()inconstructor() - Don’t perform DOM manipulations in
constructor() - Don’t call
super()with parameters in the constructor - Don’t use the
returnstatement in the constructor body
