xiaohongshu
xiaohongshu
This skill should be used when the user asks to "create lwc component", "lightning web component", "component architecture", "lwc state management", "lwc testing", "jest test", or mentions container/presentational patterns, pub-sub, or LWC best practices.
Full skill instructions
Lightning Web Components (LWC) enterprise patterns provide architectural guidance for building scalable, maintainable component libraries for Salesforce managed packages. This skill covers proven patterns for component architecture, state management, event communication, and testing strategies that enable teams to deliver high-quality, reusable components.
Apply these patterns when building component libraries that require consistency, testability, and long-term maintainability across large development teams.
Separate business logic from presentation by using container components to manage state and data operations while presentational components focus solely on rendering UI.
Container Components:
Presentational Components:
@api propertiesWhen to Use:
Benefits:
Example Structure:
accountDashboard/ // Container
accountDashboard.js // Handles @wire getAccount, state
accountDashboard.html // Minimal template
accountDashboard.css
__tests__/
accountCard/ // Presentational
accountCard.js // @api account, dispatches events
accountCard.html // Rich UI template
accountCard.css
__tests__/
See examples/containerComponent/ and examples/presentationalComponent/ for complete implementations.
Build components that work together as a coordinated system while maintaining flexibility and composability.
Pattern:
Implementation Approaches:
1. Property Pass-Through: Parent component receives configuration and passes it to children.
2. Event Coordination: Parent listens to child events and coordinates responses across siblings.
3. Context Sharing: Use CSS custom properties or data attributes for shared styling context.
When to Use:
Example Use Case:
// Compound components for a filterable list
<c-list-container filters={filters}>
<c-list-header></c-list-header>
<c-list-filter-bar onfilterchange={handleFilter}></c-list-filter-bar>
<c-list-items items={filteredItems}></c-list-items>
<c-list-footer count={itemCount}></c-list-footer>
</c-list-container>
Create abstract base components that encapsulate common functionality and extend them for specific use cases.
Pattern:
@api propertiesCommon Base Components:
Best Practices:
Use component properties decorated with @track for local, encapsulated state.
When to Use:
Best Practices:
Pass state down through properties and emit events upward for state changes.
Pattern:
@api propertiesWhen to Use:
Best Practices:
itemselected, filterchanged)Implement publish-subscribe for communication across unrelated components using Lightning Message Service or custom pub-sub.
Lightning Message Service (LMS):
When to Use:
Custom Pub-Sub Implementation:
Best Practices:
disconnectedCallback()See references/state-management.md for implementation examples.
Create JavaScript modules that act as shared services for data access, caching, and business logic.
Pattern:
When to Use:
Implementation:
// dataService.js
import getRecords from '@salesforce/apex/Controller.getRecords';
const cache = new Map();
let inFlightRequests = new Map();
export async function fetchRecords(params) {
const cacheKey = JSON.stringify(params);
if (cache.has(cacheKey)) {
return cache.get(cacheKey);
}
if (inFlightRequests.has(cacheKey)) {
return inFlightRequests.get(cacheKey);
}
const promise = getRecords(params);
inFlightRequests.set(cacheKey, promise);
try {
const result = await promise;
cache.set(cacheKey, result);
return result;
} finally {
inFlightRequests.delete(cacheKey);
}
}
Dispatch CustomEvents for component-to-component communication with proper bubbling and composition.
Event Design Principles:
detail objectbubbles: true for events crossing shadow boundariescomposed: true for events crossing component boundariesImplementation:
// Dispatching
this.dispatchEvent(new CustomEvent('itemselected', {
detail: { itemId: this.selectedId },
bubbles: true,
composed: true
}));
// Handling in parent
<c-child-component onitemselected={handleItemSelected}></c-child-component>
Best Practices:
detailHandle events at parent level for performance when dealing with many child elements.
Pattern:
event.target to identify specific childWhen to Use:
Integrate Lightning Message Service for cross-namespace and cross-framework communication.
Setup:
Implementation:
import { LightningElement, wire } from 'lwc';
import { publish, subscribe, MessageContext } from 'lightning/messageService';
import RECORD_SELECTED from '@salesforce/messageChannel/RecordSelected__c';
export default class Publisher extends LightningElement {
@wire(MessageContext)
messageContext;
handleSelect(event) {
const message = { recordId: event.detail.id };
publish(this.messageContext, RECORD_SELECTED, message);
}
}
Write comprehensive Jest tests for LWC components following enterprise testing patterns.
Test Structure:
import { createElement } from 'lwc';
import ComponentName from 'c/componentName';
describe('c-component-name', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('should render correctly with valid data', () => {
// Arrange
const element = createElement('c-component-name', {
is: ComponentName
});
// Act
document.body.appendChild(element);
// Assert
expect(element.shadowRoot.querySelector('.className')).not.toBeNull();
});
});
Container Components:
@salesforce/apex mocksPresentational Components:
Example - Testing Events:
it('should dispatch event when button clicked', () => {
const element = createElement('c-component', { is: Component });
const handler = jest.fn();
element.addEventListener('itemselected', handler);
document.body.appendChild(element);
const button = element.shadowRoot.querySelector('button');
button.click();
expect(handler).toHaveBeenCalledTimes(1);
expect(handler.mock.calls[0][0].detail).toEqual({ itemId: '123' });
});
Apex Methods:
import getAccounts from '@salesforce/apex/AccountController.getAccounts';
jest.mock(
'@salesforce/apex/AccountController.getAccounts',
() => ({ default: jest.fn() }),
{ virtual: true }
);
// In test
getAccounts.mockResolvedValue([{ Id: '001', Name: 'Test' }]);
Wire Adapters:
import { getRecord } from 'lightning/uiRecordApi';
jest.mock('lightning/uiRecordApi', () => ({
getRecord: jest.fn()
}), { virtual: true });
// In test
import { emit } from '@salesforce/sfdx-lwc-jest';
emit('getRecord', { data: mockRecord });
User Permissions:
import hasPermission from '@salesforce/userPermission/CustomPermission';
jest.mock('@salesforce/userPermission/CustomPermission', () => ({
default: true
}), { virtual: true });
See references/testing-patterns.md for comprehensive testing examples.
Use semantic HTML elements and ARIA attributes for screen reader support.
Key Practices:
<button> for clickable actions, not <div>aria-label for icon-only buttonsrole attributes when semantic HTML insufficientaria-live regions for dynamic contentaria-describedby for form field help textExample:
<button
aria-label="Close dialog"
onclick={handleClose}>
<lightning-icon icon-name="utility:close"></lightning-icon>
</button>
<div role="status" aria-live="polite" aria-atomic="true">
{statusMessage}
</div>
Ensure all interactive elements are keyboard accessible.
Requirements:
Implementation:
handleKeyDown(event) {
if (event.key === 'Escape') {
this.closeDialog();
} else if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
this.handleSelection();
}
}
Manage focus explicitly for modals, dynamic content, and navigation.
Patterns:
Use if:true and if:false Sparingly:
Prefer CSS display: none for frequently toggled elements to avoid re-rendering.
Avoid Unnecessary Re-renders:
@track judiciouslyLazy Loading:
// Dynamic import for large components
async loadEditor() {
const { default: Editor } = await import('c/richTextEditor');
// Use dynamically loaded component
}
Wire Service Best Practices:
getRecordNotifyChange for cache invalidationImperative Apex:
Example - Debouncing:
@api
handleSearch(event) {
clearTimeout(this.searchTimeout);
const searchTerm = event.target.value;
this.searchTimeout = setTimeout(() => {
this.performSearch(searchTerm);
}, 300);
}
Prevent Memory Leaks:
disconnectedCallback()Example:
disconnectedCallback() {
if (this.subscription) {
unsubscribe(this.subscription);
this.subscription = null;
}
clearTimeout(this.searchTimeout);
clearInterval(this.refreshInterval);
}
Use slots for flexible content injection and component composition.
Default Slot:
<!-- parent component -->
<div class="container">
<slot></slot>
</div>
Named Slots:
<!-- parent component -->
<div class="card">
<header>
<slot name="header"></slot>
</header>
<div class="body">
<slot></slot>
</div>
<footer>
<slot name="footer"></slot>
</footer>
</div>
<!-- usage -->
<c-card>
<h1 slot="header">Title</h1>
<p>Content</p>
<div slot="footer">Actions</div>
</c-card>
Define clear component APIs using @api properties with validation.
Best Practices:
@api properties with JSDocExample:
/**
* @typedef {Object} Item
* @property {string} id - Unique identifier
* @property {string} name - Display name
* @property {boolean} [selected] - Selection state
*/
export default class ItemList extends LightningElement {
/**
* List of items to display
* @type {Item[]}
*/
@api items = [];
/**
* Maximum number of items to display
* @type {number}
*/
@api
get maxItems() {
return this._maxItems;
}
set maxItems(value) {
this._maxItems = value > 0 ? value : 10;
}
_maxItems = 10;
}
Display clear, actionable error messages using Lightning Design System patterns.
Implementation:
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
handleError(error) {
const evt = new ShowToastEvent({
title: 'Error loading data',
message: this.getErrorMessage(error),
variant: 'error',
mode: 'sticky'
});
this.dispatchEvent(evt);
}
getErrorMessage(error) {
if (Array.isArray(error.body)) {
return error.body.map(e => e.message).join(', ');
} else if (error.body?.message) {
return error.body.message;
}
return 'An unexpected error occurred';
}
Implement null checks and default values to prevent runtime errors.
Patterns:
record?.Nameitems ?? []if (data && data.length > 0){item.name || 'N/A'}references/testing-patterns.md - Comprehensive Jest testing examples, mocking strategies, coverage patternsreferences/state-management.md - State management implementation patterns, pub-sub examples, LMS integrationexamples/containerComponent/ - Complete container component with data fetching, state management, error handlingexamples/presentationalComponent/ - Presentational component with events, slots, accessibility| Pattern | Use When | Benefits |
|---|---|---|
| Container/Presentational | Complex components with business logic | Testability, reusability, separation of concerns |
| Compound Components | Related components work together | Flexibility, coordinated behavior, composition |
| Pub-Sub | Unrelated components need communication | Decoupling, scalability, event broadcasting |
| Service Components | Shared data access needed | Caching, consistency, centralized logic |
| Event Delegation | Many interactive child elements | Performance, fewer listeners, scalability |
Apply these enterprise patterns to build maintainable, scalable LWC component libraries for Salesforce managed packages.
xiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience