Best Practices

When using complex template expressions in LWC, follow these best practices to ensure maintainable, performant, and reliable code.

Keep Expressions Simple and Readable 

While complex expressions enable powerful inline computations, prioritize readability and maintainability:

1<!-- ✅ Good - simple and clear -->
2<div>{user?.name ?? 'Guest'}</div>
3<div>{items.length > 0 ? `Found ${items.length} items` : 'No items'}</div>
4
5<!-- ❌ Avoid - too complex for inline -->
6<div>
7  {items.filter(i => i.active).map(i => i.price).reduce((a, b) => a + b, 0) / items.filter(i =>
8  i.active).length}
9</div>

Best Practice: If an expression spans multiple lines or requires significant mental parsing, it might be too complicated.

Use Getters for Complex Logic 

When logic becomes complex, extract complex calculations, formatting, or transformations to getters for better testability and reusability.

1<!-- ✅ Good - complex logic in getter -->
2<div>{totalPrice}</div>
3<div>{formattedDate}</div>
4
5<!-- ❌ Avoid - complex logic inline -->
6<div>{(subtotal + tax + shipping - discount).toFixed(2)}</div>
7<div>
8  {new Date(timestamp).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric'
9  })}
10</div>

Prefer Component Methods for Reusable Logic 

For logic that needs to be reused across multiple expressions or components, use component methods.

1<!-- ✅ Good - reusable method -->
2<div>{formatCurrency(price)}</div>
3<div>{formatCurrency(discount)}</div>
4<div>{formatCurrency(total)}</div>

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.

Tip

Test Thoroughly 

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

Avoid Deeply Nested Expressions 

Deeply nested expressions are difficult to read and maintain:

1<!-- ✅ Good - clear and readable -->
2<div>{user?.profile?.name ?? 'Anonymous'}</div>
3
4<!-- ❌ Avoid - too deeply nested -->
5<div>{user?.profile?.settings?.theme?.colors?.primary ?? 'default'}</div>

Best Practice: Flatten nested structures or use intermediate variables or getters when nesting exceeds 2-3 levels.

Use Meaningful Variable Names in Arrow Functions 

When using arrow functions in expressions, use descriptive parameter names that clearly indicate what the variable represents.

1<!-- ✅ Good - clear variable names -->
2<div>{items.map(item => item.name)}</div>
3<div>{users.filter(user => user.isActive)}</div>
4
5<!-- ❌ Avoid - unclear single-letter names -->
6<div>{items.map(x => x.name)}</div>
7<div>{users.filter(u => u.isActive)}</div>

Quote Expressions in Attributes 

Always quote complex expressions when used in attributes:

1<!-- ✅ Good - quoted complex expressions -->
2<div class="{isActive ? 'active' : 'inactive'}"></div>
3<button onclick="{() => handleClick()}">Click</button>
4
5<!-- ❌ Error - unquoted complex expressions -->
6<div class={isActive ? 'active' : 'inactive'}></div>
7<button onclick={() => handleClick()}>Click</button>

Best Practice: Quote any expression that contains operators, function calls, or anything beyond simple property access.

Consider HTML Compliance 

Always ensure expressions are HTML compliant, especially when using comparison operators:

1<!-- ✅ Good - HTML compliant -->
2<div>{age >= 18 ? 'Adult' : 'Minor'}</div>
3<div class="{bar > foo ? 'high' : 'low'}"></div>
4
5<!-- ❌ Avoid - not HTML compliant in text nodes -->
6<div>{age < 18 ? 'Minor' : 'Adult'}</div>

Best Practice: Use >= and > instead of < and <= in text node expressions, or use quoted attributes for < comparisons. See HTML Syntax Compatibility for additional details.

Monitor Performance 

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.