Newer Version Available
Best Practices for Conditional Markup
Use the <aura:if> or <aura:renderIf> tags to conditionally display markup.
Alternatively, you can conditionally set markup in JavaScript logic. Consider the
performance cost as well as code maintainability when you design components. The best design
choice depends on your use case.
<aura:if> versus <aura:renderIf>
<aura:if> is more lightweight than <aura:renderIf> as it only creates and renders the markup in its body or in the else attribute. Always try <aura:if> first when you want conditional markup.
Only consider using <aura:renderIf> if you expect to show the markup for both the true and false states, and it would require a server round trip to create the components that aren't initially rendered.
Here’s a quick comparison of <aura:if> versus <aura:renderIf>.
| <aura:if> | <aura:renderIf> | |
|---|---|---|
| Displaying | Creates and displays only one branch | Creates both branches but only displays one |
| Switching condition | Unrenders and destroys the current branch. Creates and displays the other branch. | Unrenders the current branch and renders the other branch |
| Empty branch | Creates a DOM placeholder | Creates a DOM placeholder |
Consider Alternatives to Conditional Markup
Here are some use cases where you should consider alternatives to <aura:if> or <aura:renderIf>.
- You want to toggle visibility
- Don’t use <aura:if> or <aura:renderIf> tags to toggle markup visibility. Use CSS instead. See Dynamically Showing or Hiding Markup.
- You need to nest conditional logic or use conditional logic in an iteration
- Using <aura:if> or <aura:renderIf> tags can hurt performance by creating a large number of components. Excessive use of conditional logic in markup can also lead to cluttered markup that is harder to maintain.
- Consider alternatives, such as using JavaScript logic in an init event handler instead. See Invoking Actions on Component Initialization.