Custom Events with Actions
Actions are one of the most powerful features of Svelte.
They are a lightweight alternative to a component that encapsulates logic and data into a reusable unit. They help us reuse the same logic on different elements.
While components have life cycle methods such as onMount
and onDestroy
that run when all the elements within the component are added to or removed from the DOM, actions are designed to handle the logic for individual elements, running only when that specific element is added to or removed from the DOM.
While components can receive and react to prop changes, you can pass data to actions from a parent component to a child component. The actions will react when the data is changed and you can specify how the action should react when that data changes.
Actions are simple yet amazingly versatile. You can use them for various things. In this and the following chapters, we are going to explore some of the use cases of actions.
One of...