Best Practices
When using complex template expressions in LWC, follow these best practices to ensure maintainable, performant, and reliable code.
While complex expressions enable powerful inline computations, prioritize readability and maintainability:
Best Practice: If an expression spans multiple lines or requires significant mental parsing, it might be too complicated.
When logic becomes complex, extract complex calculations, formatting, or transformations to getters for better testability and reusability.
For logic that needs to be reused across multiple expressions or components, use component methods.
Component methods are easier to test, debug, and reuse than inline expressions. Put your methods and functions in a separate API module component that you can easily import into any component that uses them.
Since complex template expressions are experimental, thorough testing is essential. Write comprehensive tests for any component using complex template expressions.
- Unit Tests: Test the JavaScript methods and getters used in expressions
- Integration Tests: Verify that expressions render correctly in components
- Edge Cases: Test with
null,undefined, empty arrays, and boundary values - HTML Compliance: Verify that expressions work correctly in both text nodes and attributes
- Browser Compatibility: Test across different browsers and versions
Deeply nested expressions are difficult to read and maintain:
Best Practice: Flatten nested structures or use intermediate variables or getters when nesting exceeds 2-3 levels.
When using arrow functions in expressions, use descriptive parameter names that clearly indicate what the variable represents.
Always quote complex expressions when used in attributes:
Best Practice: Quote any expression that contains operators, function calls, or anything beyond simple property access.
Always ensure expressions are HTML compliant, especially when using comparison operators:
Best Practice: Use >= and > instead of < and <= in text node expressions, or use quoted attributes for < comparisons. See HTML Syntax Compatibility for additional details.
While complex expressions are performant, be mindful of:
- Repeated Calculations: If an expression is used multiple times, consider caching the result in a getter
- Large Arrays: Operations on large arrays (filter, map, reduce) can impact performance
- Frequent Re-renders: Expressions are re-evaluated on every render; complex expressions can have a larger-than-expected impact
Best Practice: Profile your components and optimize expressions that are called frequently or operate on large datasets.