⚡
SF DEV TOOLKIT
Apex · SOQL · LWC · Patterns
API v62.0
Lightning Web Components
LWC Patterns & Lifecycle
Modern LWC patterns covering lifecycle hooks, wire adapters, reactive properties, events, and performance optimization.
Component Lifecycle Hooks
constructor()
Called when: Component is created (before inserted into DOM)
First hook fired. Component not yet attached to DOM — no access to host element, attributes, or public properties. Cannot access child elements. Must call super() first. Use for initializing component state only.
Use for: Initialize non-reactive class properties, set default values
Don't: Access this.template, modify DOM, or call external APIs
connectedCallback()
Called when: Component inserted into DOM
Most important hook for initialization. Component is now in DOM but not yet rendered. Fires every time component is inserted (can fire multiple times if component is moved). Safe to access host element via this.template. Perfect for subscriptions, event listeners, and data fetching.
Use for: Subscribe to events, fetch initial data, register message channel subscribers, set up event listeners
Example: Subscribe to Platform Events, Lightning Message Service
renderedCallback()
Called when: Component finishes rendering (after every render)
Fires after every render cycle — can fire multiple times. Component and children are fully rendered. Use sparingly — infinite loops possible if you mutate reactive properties here. Ideal for DOM manipulation, focusing elements, or initializing third-party libraries that require rendered DOM.
Use for: Focus an input, initialize third-party JS libraries (charts, maps), measure DOM element dimensions
Warning: Don't update @track/@api properties here (causes re-render loop)
disconnectedCallback()
Called when: Component removed from DOM
Cleanup hook. Fires when component is removed from DOM (navigation, conditional rendering). Essential for preventing memory leaks — unsubscribe from events, clear intervals/timeouts, cancel pending async operations. Does not fire on page refresh (entire page unloads).
Use for: Unsubscribe from Platform Events, LMS channels, remove event listeners, clear setInterval/setTimeout
Critical: Always pair connectedCallback subscriptions with disconnectedCallback cleanup
errorCallback(error, stack)
Called when: Error in child component's lifecycle hook or event handler
Error boundary for child components. Catches errors from descendant components, not from the component itself. Use to display fallback UI or log errors to external service. Error propagates up tree — parent's errorCallback catches if child doesn't handle it.
Use for: Log errors to analytics, display error messages to users, render fallback UI
Note: Only catches errors in children, not in own component
@wire vs Imperative Apex — When to Use Each Best Practices
// ── @wire: Use for REACTIVE data that auto-refreshes ──
import { wire } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';

@wire(getAccounts, { status: '$filterStatus' })
wiredAccounts({ error, data }) {
    if (data) {
        this.accounts = data;
        this.error = undefined;
    } else if (error) {
        this.error = error;
        this.accounts = undefined;
    }
}

// When filterStatus changes, @wire automatically re-fetches data
// Use @wire for: read-only data, lists that update based on filters, dashboard widgets

// ── Imperative: Use for USER-TRIGGERED actions (button clicks) ──
import createAccount from '@salesforce/apex/AccountController.createAccount';

async handleSave() {
    this.isLoading = true;
    try {
        const result = await createAccount({ name: this.accountName });
        this.dispatchEvent(new ShowToastEvent({ 
            title: 'Success', 
            message: 'Account created', 
            variant: 'success' 
        }));
        // Refresh wire adapter data after mutation
        await refreshApex(this.wiredAccountsResult);
    } catch (error) {
        this.handleError(error);
    } finally {
        this.isLoading = false;
    }
}

// Use imperative for: DML operations, user-triggered actions, one-time fetches
⚠ @track is Deprecated
As of Winter '23, @track is no longer needed for primitive reactivity. All fields are reactive by default. Only use @track for objects/arrays when you need to trigger re-render on nested property mutation: this.account.name = 'New' (won't re-render without @track on the object). Best practice: use spread operator to create new object instead of mutating: this.account = {...this.account, name: 'New'} (triggers reactivity without @track).
accountManager.js — Complete Lifecycle Example LWC
import { LightningElement, api, wire } from 'lwc';
import { getRecord, getFieldValue, updateRecord } from 'lightning/uiRecordApi';
import { refreshApex } from '@salesforce/apex';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { 
    subscribe, unsubscribe, onError 
} from 'lightning/empApi';

import NAME_FIELD from '@salesforce/schema/Account.Name';
import REVENUE_FIELD from '@salesforce/schema/Account.AnnualRevenue';

export default class AccountManager extends LightningElement {
    @api recordId;
    wiredAccountResult;
    platformEventSubscription;
    isLoading = false;
    error;

    // ── CONSTRUCTOR: Initialize non-reactive state ──
    constructor() {
        super();
        // Can't access this.template yet
        this.hasInitialized = false;
    }

    // ── CONNECTED: Subscribe to Platform Events ──
    connectedCallback() {
        this.subscribeToPlatformEvents();
        this.registerErrorListener();
    }

    // ── WIRE: Reactive data fetching ──
    @wire(getRecord, {
        recordId: '$recordId',
        fields: [NAME_FIELD, REVENUE_FIELD]
    })
    wiredAccount(result) {
        this.wiredAccountResult = result;
        if (result.error) {
            this.error = result.error.body.message;
        }
    }

    // ── RENDERED: DOM is ready, focus input if first render ──
    renderedCallback() {
        if (!this.hasInitialized) {
            const input = this.template.querySelector('lightning-input');
            if (input) {
                input.focus();
                this.hasInitialized = true;
            }
        }
    }

    // ── DISCONNECTED: Cleanup subscriptions ──
    disconnectedCallback() {
        if (this.platformEventSubscription) {
            unsubscribe(this.platformEventSubscription, response => {
                console.log('Unsubscribed from Platform Event');
            });
        }
    }

    // ── ERROR BOUNDARY: Catch errors from child components ──
    errorCallback(error, stack) {
        console.error('Error from child component:', error, stack);
        this.error = 'Something went wrong. Please refresh.';
    }

    // ── GETTERS: Computed properties ──
    get accountName() {
        return getFieldValue(this.wiredAccountResult.data, NAME_FIELD);
    }

    get hasError() {
        return !!this.error;
    }

    // ── PLATFORM EVENTS: Subscribe in connected, unsubscribe in disconnected ──
    subscribeToPlatformEvents() {
        const channelName = '/event/Account_Updated__e';
        subscribe(channelName, -1, response => {
            const payload = response.data.payload;
            if (payload.Account_Id__c === this.recordId) {
                refreshApex(this.wiredAccountResult);
            }
        }).then(subscription => {
            this.platformEventSubscription = subscription;
        });
    }

    registerErrorListener() {
        onError(error => {
            console.error('Platform Event Error:', error);
        });
    }

    // ── USER ACTIONS: Imperative Apex calls ──
    async handleSave() {
        this.isLoading = true;
        try {
            const fields = { Id: this.recordId, Name: this.accountName };
            await updateRecord({ fields });
            await refreshApex(this.wiredAccountResult);
            this.dispatchEvent(new ShowToastEvent({
                title: 'Success',
                message: 'Account updated',
                variant: 'success'
            }));
        } catch (error) {
            this.error = error.body.message;
        } finally {
            this.isLoading = false;
        }
    }
}
Performance & Memory Best Practices Optimization
// ── 1. Use getters for computed properties (cached until dependency changes) ──
get filteredAccounts() {
    return this.accounts.filter(a => a.AnnualRevenue > 1000000);
}
// Better than computing in template: {filteredAccounts} vs {accounts.filter(...)}

// ── 2. Debounce user input to reduce server calls ──
handleSearchChange(event) {
    window.clearTimeout(this.delayTimeout);
    const searchKey = event.target.value;
    this.delayTimeout = setTimeout(() => {
        this.searchKey = searchKey;  // This triggers @wire re-fetch
    }, 300);
}

// ── 3. Use if:true/if:false for conditional rendering (not display: none) ──
// ✓ GOOD: Component not created at all if condition false
<template lwc:if={showDetails}>
    <c-expensive-component></c-expensive-component>
</template>
// ✗ BAD: Component created but hidden (wastes memory)
<div style={hideStyle}><c-expensive-component></c-expensive-component></div>

// ── 4. Avoid renderedCallback infinite loops ──
renderedCallback() {
    // ✗ BAD: Causes infinite re-render
    // this.count++;
    
    // ✓ GOOD: Use flag to run only once
    if (!this.chartInitialized) {
        this.initializeChart();
        this.chartInitialized = true;
    }
}

// ── 5. Clean up in disconnectedCallback to prevent memory leaks ──
connectedCallback() {
    this.intervalId = setInterval(() => this.refreshData(), 5000);
}
disconnectedCallback() {
    if (this.intervalId) {
        clearInterval(this.intervalId);
    }
}