Skip to main content
Nesting components and iterating over data are essential patterns for building dynamic, data-driven user interfaces in Lightning Web Components. This guide covers advanced composition techniques including iteration, conditional rendering, and building complete experiences.

Component Iteration

When you need to display multiple instances of a child component based on an array of data, use the for:each directive.

Using for:each

The for:each directive iterates over an array and creates a component instance for each item. compositionIteration.js
compositionIteration.html

Key Requirements

Always include a key directive when using for:each. The key must be unique for each item and helps the framework efficiently update the DOM when the list changes.

for:each Directives

Example with Index

Building Complete Experiences

You can compose multiple child components together to create rich, interactive experiences.

Contact Search Example

This example combines input handling, data fetching, iteration, and error handling: compositionContactSearch.js
compositionContactSearch.html
This example demonstrates:
1

User input handling

The lightning-input component captures search text
2

Debouncing

Delays the Apex call to reduce server load while typing
3

Data fetching

Calls an Apex method to retrieve matching contacts
4

Dynamic rendering

Uses for:each to render a contact tile for each result
5

Error handling

Displays an error panel if the Apex call fails

Conditional Rendering

Combine iteration with conditional rendering to handle different states.

Using lwc:if and lwc:elseif

Nesting Depth

Components can be nested multiple levels deep. Each level can have its own logic and state.
While there’s no hard limit on nesting depth, deeply nested components can be harder to maintain. Consider your component hierarchy carefully.

Performance Considerations

Efficient Iteration

1

Use unique keys

Always provide stable, unique keys for iterated items
2

Avoid unnecessary re-renders

Only update the data when it actually changes
3

Limit iteration size

For large datasets, consider pagination or virtual scrolling
4

Use conditional rendering

Don’t render components that aren’t needed

Debouncing Example

The contact search example demonstrates debouncing to reduce unnecessary server calls:

Common Patterns

Empty State Handling

Loading State

Next Steps

Events

Learn how child components communicate with parents

App Builder Integration

Expose your components in Lightning App Builder