lifecycle-hooks

Use when building or reviewing Lightning Web Components — specifically lifecycle management, wire service, memory leak prevention, navigation, and Lightning Locker Service constraints. Triggers: 'LWC', 'connectedCallback', 'renderedCallback', 'memory leak', 'NavigationMixin', 'wire'. NOT for Aura components.

Best use case

lifecycle-hooks is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Use when building or reviewing Lightning Web Components — specifically lifecycle management, wire service, memory leak prevention, navigation, and Lightning Locker Service constraints. Triggers: 'LWC', 'connectedCallback', 'renderedCallback', 'memory leak', 'NavigationMixin', 'wire'. NOT for Aura components.

Teams using lifecycle-hooks should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/lifecycle-hooks/SKILL.md --create-dirs "https://raw.githubusercontent.com/PranavNagrecha/AwesomeSalesforceSkills/main/skills/lwc/lifecycle-hooks/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/lifecycle-hooks/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How lifecycle-hooks Compares

Feature / Agentlifecycle-hooksStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Use when building or reviewing Lightning Web Components — specifically lifecycle management, wire service, memory leak prevention, navigation, and Lightning Locker Service constraints. Triggers: 'LWC', 'connectedCallback', 'renderedCallback', 'memory leak', 'NavigationMixin', 'wire'. NOT for Aura components.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

You are a Salesforce expert in Lightning Web Component lifecycle design. Your goal is to build LWCs that are memory-safe, performant, accessible, and aligned with Salesforce runtime constraints.

## Before Starting

Check for `salesforce-context.md` in the project root. If present, read it first — particularly whether Experience Cloud is involved, whether the org uses standard Salesforce LWC, and whether third-party libraries are approved.

Gather if not available:
- Is this a new component or review of an existing one?
- Does it use Apex, wire adapters, or Lightning Data Service?
- Does it run in Lightning Experience, mobile, Experience Cloud, or multiple contexts?
- Does it add event listeners, timers, navigation, or external scripts?

## How This Skill Works

### Mode 1: Build from Scratch

1. Define the public API and the data contract first.
2. Choose the lightest data pattern that fits: LDS, wire adapter, then Apex if needed.
3. Plan what belongs in each lifecycle hook before writing code.
4. Design loading, data, and error states together.
5. Use Salesforce-native navigation, notifications, and static resource loading patterns.

### Mode 2: Review Existing

1. Check `connectedCallback` and `disconnectedCallback` for cleanup symmetry.
2. Verify `renderedCallback` is guarded and not mutating reactive state blindly.
3. Confirm `@api` props are treated as immutable inputs.
4. Check wire handlers for both success and error branches.
5. Flag `window.location`, global DOM access, `alert()`, or raw external script tags.

### Mode 3: Troubleshoot

1. If the component leaks or misbehaves after navigation, inspect listener and timer cleanup.
2. If it rerenders endlessly, inspect `renderedCallback` and any reactive mutation it triggers.
3. If data appears stale or blank, compare the chosen data pattern with the actual use case.
4. If the UI breaks only in mobile or Experience Cloud, inspect navigation and CSP assumptions.
5. Fix the lifecycle contract first, then the cosmetic issue.

## LWC Lifecycle Rules

### Hook Reference

| Hook | Use For | Avoid |
|------|---------|-------|
| `constructor()` | Cheap setup only | DOM access |
| `connectedCallback()` | Event listeners, initial orchestration | Child DOM queries not yet rendered |
| `renderedCallback()` | One-time DOM work with a guard | Repeated reactive mutations |
| `disconnectedCallback()` | Cleanup listeners, timers, subscriptions | Business logic that should have happened earlier |
| `errorCallback()` | Child-error boundaries | Replacing async error handling everywhere |

### High-Value Patterns

- Store bound event handlers and remove them in `disconnectedCallback`.
- Guard `renderedCallback` with a boolean when doing one-time initialization.
- Treat `@api` objects as immutable. Clone before editing.
- Prefer `NavigationMixin` over URL mutation.
- Prefer `ShowToastEvent` or inline states over blocking browser dialogs.
- Use Static Resources with `loadScript` and `loadStyle`; do not inject external scripts directly.
- Keep full code examples in `references/examples.md` rather than repeating them in the main skill.

#
## Recommended Workflow

Step-by-step instructions for an AI agent or practitioner activating this skill:

1. Gather context — confirm the org edition, relevant objects, and current configuration state
2. Review official sources — check the references in this skill's well-architected.md before making changes
3. Implement or advise — apply the patterns from Core Concepts and Common Patterns sections above
4. Validate — run the skill's checker script and verify against the Review Checklist below
5. Document — record any deviations from standard patterns and update the template if needed

---

## Review Checklist

- [ ] Listener or timer setup has matching cleanup
- [ ] `renderedCallback` is idempotent
- [ ] Wire or Apex data path handles loading, success, and error
- [ ] DOM access stays within `this.template`
- [ ] Navigation and feedback use Salesforce-supported APIs
- [ ] Third-party libraries load through Static Resources

## Salesforce-Specific Gotchas

| Gotcha | What to do |
|---|---|
| `window.location` breaks across Salesforce containers | Use `NavigationMixin` so Lightning Experience, mobile, and Experience Cloud stay consistent. |
| `alert()` is not acceptable UX in Lightning | Use `ShowToastEvent` or deliberate inline UI states. |
| Lightning Web Security isolates DOM boundaries | Reaching into child shadow DOM is brittle and often blocked. |
| `renderedCallback` runs after every render | Guard reactive-state changes inside it; otherwise you create a rerender loop. |
| `@api` values are input contracts, not mutable local state | Clone them before changes. |
| External script loading fails silently without handling | Always catch `loadScript` or `loadStyle` failures. |

## Proactive Triggers

Surface these WITHOUT being asked:

| Pattern | Severity | Why / Fix |
|---|---|---|
| Global event listeners with no cleanup | Critical | Memory leak and Experience Cloud bug magnet. |
| `renderedCallback` with no guard | High | Infinite rerender risk. |
| `window.location` or raw anchor hacks for navigation | High | Use `NavigationMixin`. |
| `document.querySelector()` or child shadow DOM access | High | Violates component isolation. |
| External `<script>` tags or remote JS assumptions | Critical | Use Static Resources. |
| Data path with no error state | Medium | Blank components are an operational failure. |

## Output Artifacts

| When you ask for... | You get... |
|---------------------|------------|
| New component scaffold | Lifecycle-safe JS and HTML guidance with state handling |
| LWC review | Findings on leaks, navigation, DOM isolation, and async state design |
| Troubleshoot memory leak | Root cause plus cleanup fix |

## Related Skills

- **apex/soql-security**: Apex called from LWC still needs sharing and CRUD/FLS enforcement.
- **admin/flow-for-admins**: Screen Flows may replace simpler custom UI requirements.

Related Skills

lwc-styling-hooks

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when theming Lightning base components or custom LWCs with SLDS Styling Hooks — CSS custom properties such as `--slds-c-button-color-background`, `--slds-g-color-brand-base-50`, and `--sds-c-*` — across app, page, component, or Experience Cloud scopes, including SLDS 2 (2e) migration via SLDS Validator / Linter and dark-mode surface work. Triggers: 'how to theme lightning-button', 'custom color without overriding slds classes', 'slds 2 migration for lwc', '--slds-c-button-color-background doesn't work', 'experience cloud brand color in lwc', 'dark mode lwc base components'. NOT for raw CSS overrides that target SLDS internal class names — those break on upgrade — and NOT for Experience Cloud theme designer work broader than styling hooks (palette pickers, custom CSS files, branding sets, theme layouts).

revenue-lifecycle-management

8
from PranavNagrecha/AwesomeSalesforceSkills

Use this skill when implementing or troubleshooting Salesforce Revenue Lifecycle Management (RLM) — the native Revenue Cloud product covering order-to-cash lifecycle, Dynamic Revenue Orchestrator (DRO) fulfillment plan design, asset amendments, billing schedule creation via Connect API, and invoice management. Triggers on: Dynamic Revenue Orchestrator, RLM order decomposition, DRO fulfillment swimlanes, native Revenue Cloud billing schedule, asset lifecycle management Salesforce. NOT for CPQ quoting or pricing rules (use cpq-* skills), not for the legacy Salesforce Billing managed package with blng__* objects (different product entirely), not for standard Order objects without Revenue Cloud features.

entitlement-apex-hooks

8
from PranavNagrecha/AwesomeSalesforceSkills

Use this skill when writing Apex triggers or classes that interact with CaseMilestone records — completing milestones, detecting violations, or reacting to SLA state changes. Trigger keywords: CaseMilestone trigger, auto-complete milestone Apex, milestone violation polling, CompletionDate write pattern. NOT for entitlement process admin setup, milestone configuration in Setup UI, or Flow-based milestone actions.

subscription-lifecycle-requirements

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when documenting, reviewing, or gathering requirements for Salesforce CPQ subscription lifecycle behavior: how amendments, renewals, upgrades, downgrades, and cancellations must work for a specific business. Trigger keywords: subscription requirements, amendment requirements, renewal requirements, proration requirements, co-termination, subscription ledger, upgrade downgrade policy. NOT for CPQ setup or configuration, not for Apex amendment API implementation, and not for Revenue Cloud advanced order management.

donor-lifecycle-requirements

8
from PranavNagrecha/AwesomeSalesforceSkills

Requirements mapping for the full donor lifecycle in NPSP or Nonprofit Cloud: acquisition stage design, moves management for cultivation and solicitation, upgrade path design, lapsed donor re-engagement strategy, and segmentation for portfolio management. NOT for marketing automation execution, email campaign configuration, or recurring donation implementation.

xss-and-injection-prevention

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when writing or reviewing Visualforce pages, Apex controllers, or LWC components that output user-supplied data, build dynamic queries, or construct HTTP responses. Triggers: 'XSS in Visualforce', 'SOQL injection vulnerability', 'how to encode output in Apex', 'JSENCODE Visualforce', 'open redirect prevention'. NOT for Apex CRUD/FLS enforcement (use soql-security or apex-crud-and-fls), NOT for Shield encryption (use shield-encryption-key-management), NOT for AppExchange security review process (use secure-coding-review-checklist).

visualforce-security-and-modernization

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when hardening or modernizing legacy Visualforce pages — covers the platform CSRF token model and when disabling it is a security regression, view state encryption guarantees and the 170 KB ceiling, FLS/CRUD enforcement gaps on `<apex:outputField>` and on getters that return sObjects, `<apex:includeScript>` interaction with the org Content Security Policy, hosting LWC inside a VF page via `lightning:container` / `lightning-out`, and the retire-vs-harden-vs-leave-alone decision for an inventory of legacy pages. Triggers: 'should I rewrite this Visualforce page in LWC', 'CSRF protection disabled on Visualforce page is that safe', 'community user sees a field they should not on a Visualforce page', 'view state encryption is that enough for sensitive data', 'how do I host an LWC inside a Visualforce page', 'apex:dynamicComponent and apex:actionFunction safe to keep'. NOT for greenfield Visualforce architecture (use apex/visualforce-fundamentals — controller types, view state pattern selection, PDF rendering); NOT for Visualforce email template authoring (use apex/visualforce-email-templates if/when that skill is authored); NOT for general Apex security review across triggers and async (use apex/soql-security and security/secure-coding-review-checklist).

transaction-security-policies

8
from PranavNagrecha/AwesomeSalesforceSkills

Transaction Security policy creation and configuration: condition builder, enhanced policies, enforcement actions (block, MFA, notification, end session), real-time monitoring mode, and policy troubleshooting. NOT for Event Monitoring log analysis or Shield Event Monitoring setup (use event-monitoring). NOT for Apex testing or debug-log analysis.

sso-saml-troubleshooting

8
from PranavNagrecha/AwesomeSalesforceSkills

Diagnosing broken SAML SSO into Salesforce — IdP-initiated vs SP-initiated flows, signing-certificate validity / expiry, NameID format mismatches, RelayState handling, audience / entityId / issuer mismatches, clock skew, the SAML Assertion Validator in Setup, the Login History debug log, and the My Domain prerequisite for SSO. Covers the standard diagnostic loop: read the SAML response, identify which check failed, fix at the IdP or SP. NOT for OAuth / OpenID Connect SSO (see security/oauth-openid-troubleshooting), NOT for setting up SSO from scratch (see security/sso-saml-setup).

shield-kms-byok-setup

8
from PranavNagrecha/AwesomeSalesforceSkills

Configure Shield Platform Encryption with customer-supplied (BYOK) or customer-held (Cache-Only Key Service) tenant secrets, rotate them, and recover. NOT for Classic Encryption or field masking.

shield-event-log-retention-strategy

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing Salesforce Shield Event Monitoring retention, SIEM routing, and storage-tier strategy — which event types to keep, for how long, where, and how to answer audit queries across hot/warm/cold tiers. Triggers: 'shield event log retention', 'route event monitoring to splunk', 'how long to keep login history', 'siem salesforce integration', 'event monitoring storage tier'. NOT for enabling Shield (see salesforce-shield-deployment).

session-management-and-timeout

8
from PranavNagrecha/AwesomeSalesforceSkills

Use this skill when configuring session timeout values, concurrent session limits, session IP locking, or logout behavior in Salesforce. Covers org-wide session settings, profile-level overrides, Connected App session policies, and Metadata API SecuritySettings deployment. NOT for OAuth token refresh flows, login IP ranges, or MFA/identity-provider configuration.