Reader small image

You're reading from  Real-World Svelte

Product typeBook
Published inDec 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781804616031
Edition1st Edition
Languages
Right arrow
Author (1)
Tan Li Hau
Tan Li Hau
author image
Tan Li Hau

Tan Li Hau is a frontend developer at Shopee and a core maintainer of Svelte. He has delivered multiple conference talks and workshops on Svelte. Passionate about sharing his knowledge, Li Hau regularly contributes to the community through blog posts, YouTube videos, and books. He aspires to inspire others to explore and learn about Svelte and other modern web technologies.
Read more about Tan Li Hau

Right arrow

Composing lifecycle functions into reusable hooks

So far, we’ve mainly talked about reusing one lifecycle function. However, there’s nothing stopping us from grouping multiple lifecycle functions to perform a function.

Here’s an excerpt from the example at https://svelte.dev/examples/update. The example shows a list of messages. When new messages are added to the list, the container will automatically scroll to the bottom to show the new message. In the code snippet, we see that this automatic scrolling behavior is achieved by using a combination of beforeUpdate and afterUpdate:

<script>
  import { beforeUpdate, afterUpdate } from 'svelte';
  let div;
  let autoscroll;
  beforeUpdate(() => {
    autoscroll = div && (div.offsetHeight + div.scrollTop) > (div.scrollHeight - 20);
  });
  afterUpdate(() => {
    if (autoscroll) div.scrollTo(0, div.scrollHeight);
  });
</script>
<div bind:this={div} />

To reuse this autoscroll logic in other components, we can extract the beforeUpdate and afterUpdate logic together into a new function:

export function setupAutoscroll() {
  let div;
  let autoscroll;
  beforeUpdate(() => {
    autoscroll = div && (div.offsetHeight + div.scrollTop) > (div.scrollHeight - 20);
  });
  afterUpdate(() => {
    if (autoscroll) div.scrollTo(0, div.scrollHeight);
  });
  return {
  setDiv(_div) {
  div = _div;
    },
  };
}

We can then use the extracted function, setupAutoScroll, in any component:

<script>
  import { setupAutoscroll } from './autoscroll';
  const { setDiv } = setupAutoscroll();
  let div;
  $: setDiv(div);
</script>
<div bind:this={div} />

In the refactored setupAutoscroll function, we return a setDiv function to allow us to update the reference of the div used within the setupAutoscroll function.

As you’ve seen, by adhering to the one rule of calling lifecycle functions during component initialization, you can compose multiple lifecycle functions into reusable hooks. What you’ve learned so far is sufficient for composing lifecycle functions, but there are more alternatives on the horizon. In the upcoming chapters, you’ll explore Svelte actions in Chapter 5 and the Svelte store in Chapter 8, expanding your options further. Here’s a sneak peek at some of these alternatives.

An alternative implementation could be to make div a writable store and return it from the setupAutoscroll function. This way, we could bind to the div writable store directly instead of having to call setDiv manually.

Alternatively, we could return a function that follows the Svelte action contract and use the action on the div:

export function setupAutoscroll() {
  let div;
  // ...
  return function (node) {
    div = node;
    return {
      destroy() {
        div = undefined;
      },
    };
  };
}

setupAutoscroll now returns an action, and we use the action on our div container:

<script>
  import { setupAutoscroll } from './autoscroll';
  const autoscroll = setupAutoscroll();
</script>
<div use:autoscroll />

We will discuss the Svelte action contract in more detail later in the book.

We’ve seen how we can extract lifecycle functions into a separate file and reuse it in multiple Svelte components. Currently, the components call the lifecycle functions independently and function as standalone units. Is it possible to synchronize or coordinate actions across components that uses the same lifecycle functions? Let’s find out.

Previous PageNext Page
You have been reading a chapter from
Real-World Svelte
Published in: Dec 2023Publisher: PacktISBN-13: 9781804616031
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Tan Li Hau

Tan Li Hau is a frontend developer at Shopee and a core maintainer of Svelte. He has delivered multiple conference talks and workshops on Svelte. Passionate about sharing his knowledge, Li Hau regularly contributes to the community through blog posts, YouTube videos, and books. He aspires to inspire others to explore and learn about Svelte and other modern web technologies.
Read more about Tan Li Hau