Welcome back! In the previous lesson, you explored how to use the #if
, else-if
and else
blocks in Svelte to manage control flow. These constructs allowed you to conditionally render content and iterate over lists, enhancing the interactivity and responsiveness of your applications. Today, we will build on that foundation by focusing on optimizing list rendering using keyed #each
blocks. This lesson will help you understand how to efficiently update the DOM when items are added or removed from a list, ensuring your applications run smoothly and efficiently.
Non-keyed #each
blocks in Svelte allow you to iterate over arrays and render lists dynamically. However, they come with limitations, particularly when it comes to updating the DOM. When you modify the value of an #each
block, Svelte adds and removes DOM nodes at the end of the block and updates any values that have changed. This can lead to DOM node misalignment, where elements do not update as expected.
Consider the following example:
