Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Real-World Svelte
Real-World Svelte

Real-World Svelte: Supercharge your apps with Svelte 4 by mastering advanced web development concepts

eBook
$21.99 $31.99
Paperback
$31.98 $39.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
Table of content icon View table of contents Preview book icon Preview Book

Real-World Svelte

Lifecycles in Svelte

Svelte is a frontend framework. You can use Svelte to build websites and web applications. A Svelte application is made up of components. You write a Svelte component within a file with .svelte extension. Each .svelte file is one Svelte component.

When you create and use a Svelte component, the component goes through various stages of the component lifecycle. Svelte provides lifecycle functions, allowing you to hook into the different stages of the component.

In this chapter, we will start by talking about the various lifecycles and the lifecycle functions in Svelte. With a clear idea of lifecycles in mind, you will then learn the basic rule of using the lifecycle functions. This is essential, as you will see that this understanding will allow us to use the lifecycle functions in a lot of creative ways.

This chapter contains sections on the following topics:

  • What are Svelte lifecycle functions?
  • The rule of calling lifecycle functions
  • How to reuse and compose lifecycle functions

Technical requirements

Writing Svelte applications is very easy and does not require any paid tools. Despite the added value of most paid tools, we decided to use only free tools to make the content of this book available to you without any limitations.

You will require the following:

All the code examples for this chapter can be found on GitHub at: https://github.com/PacktPublishing/Real-World-Svelte/tree/main/Chapter01

Code for all chapters can be found at https://github.com/PacktPublishing/Real-World-Svelte.

Understanding the Svelte lifecycle functions

When using a Svelte component, it goes through different stages throughout its lifetime: mounting, updating, and destroying. This is similar to a human being. We go through various stages in our lifetime, such as birth, growth, old age, and death, throughout our lifetime. We call the different stages lifecycles.

Before we talk about lifecycles in Svelte, let’s look at a Svelte component.

<script>
  import { onMount, beforeUpdate, afterUpdate, onDestroy } from 'svelte';
  let count = 0;
  onMount(() => { console.log('onMount!'); });
  beforeUpdate(() => { console.log('beforeUpdate!'); });
  afterUpdate(() => { console.log('afterUpdate!'); });
  onDestroy(() => { console.log('onDestroy!'); });
</script>
<button on:click={() => { count ++; }}>
  Counter: {count}
</button>

Can you tell me when each part of the code is executed?

Not every part of the code is executed at once; different parts of the code are executed at different stages of the component lifecycle.

A Svelte component has four different lifecycle stages: initializing, mounting, updating, and destroying.

Initializing the component

When you create a component, the component first goes through the initialization phase. You can think of this as the setup phase, where the component sets up its internal state.

This is where lines 2–7 are being executed.

The count variable is declared and initialized. The onMount, beforeUpdate, afterUpdate, and onDestroy lifecycle functions are called, with callback functions passed in, to register them at the specific stages of the component lifecycles.

After the component is initialized, Svelte starts to create elements in the template, in this case, a <button> element and text elements for "Counter: " and {count}.

Mounting the component

After all the elements are created, Svelte will insert them in order into the Document Object Model (DOM). This is called the mounting phase, where elements are mounted onto the DOM.

If you add Svelte actions to an element, then the actions are called with the element:

<script>
  function action(node) {}
</script>
<div use:action>

We will explore Svelte actions in more depth in Chapter 5 to 7.

If and when you add event listeners to the element, this is when Svelte will attach the event listeners to the element.

In the case of the preceding example, Svelte attaches the click event listener onto the button after it is inserted into the DOM.

When we add bindings to an element, the bound variable gets updated with values from the element:

<script>
  let element;
</script>
<div bind:this={element} />

This is when the element variable gets updated with the reference to the <div> element created by Svelte.

If and when you add transitions to an element, this is when the transitions are initialized and start playing.

The following snippet is an example of adding a transition to an element. You can add a transition to an element using the transition:, in:, and out: directives. We will explore more about Svelte transitions in Chapter 13 to 15:

<div in:fade />

After all the directives, use: (actions), on: (event listeners), bind: bindings, in:, transition: (transitions), are processed, the mounting phase comes to an end by calling all the functions registered in the onMount lifecycle functions.

This is when the function on line 4 is executed, and you will see "onMount!" printed in the logs.

Updating the component

When you click on the button, the click event listener is called. The function on line 9 is executed. The count variable is incremented.

Right before Svelte modifies the DOM based on the latest value of the count variable, the functions registered in the beforeUpdate lifecycle function are called.

The function on line 5 is executed, and you will see the text "beforeUpdate!" printed in the logs.

At this point, if you attempt to retrieve the text content within the button, it would still be "Counter: 0".

Svelte then proceeds to modify the DOM, updating the text content of the button to "Counter: 1".

After updating all the elements within the component, Svelte calls all the functions registered in the afterUpdate lifecycle function.

The function on line 6 is executed, and you will see the text "afterUpdate!" printed in the logs.

If you click on the button again, Svelte will go through another cycle of beforeUpdate, and then update the DOM elements, and then afterUpdate.

Destroying the component

A component that is conditionally shown to a user will remain while the condition holds; when the condition no longer holds, Svelte will proceed to destroy the component.

Let’s say the component in our example now enters the destroy stage.

Svelte calls all the functions registered in the onDestroy lifecycle function. The function on line 7 is executed, and you will see the text "onDestroy!" printed in the logs.

After that, Svelte removes the elements from the DOM.

Svelte then cleans up the directives if necessary, such as removing the event listeners and calling the destroy method from the action.

And that’s it! If you try to recreate the component again, a new cycle starts again.

The Svelte component lifecycle starts with initializing, mounting, updating, and destroying. Svelte provides lifecycle methods, allowing you to run functions at different stages of the component.

Since the component lifecycle functions are just functions exported from 'svelte', can you import and use them anywhere? Are there any rules or constraints when importing and using them?

Let’s find out.

The one rule for calling lifecycle functions

The only rule for calling component lifecycle functions is that you should call them during component initialization. If no component is being initialized, Svelte will complain by throwing an error.

Let’s look at the following example:

<script>
  import { onMount } from 'svelte';
  function buttonClicked() {
    onMount(() => console.log('onMount!'));
  }
</script>
<button on:click={buttonClicked} />

When you click on the button, it will call buttonClicked, which will call onMount. As no component is being initialized when onMount is being called, (the component above has initialized and mounted by the time you click on the button), Svelte throws an error:

Error: Function called outside component initialization

Yes, Svelte does not allow lifecycle functions to be called outside of the component initialization phase. This rule dictates when you can call the lifecycle functions. What it does not dictate is where or how you call the lifecycle functions. This allows us to refactor lifecycle functions and call them in other ways.

Refactoring lifecycle functions

If you look carefully at the rule for calling lifecycle functions, you will notice that it is about when you call them, and not where you call them.

It is not necessary to call lifecycle functions at the top level within the <script> tag.

In the following example, the setup function is called during component initialization, and in turn calls the onMount function:

<script>
  import { onMount } from 'svelte';
  setup();
  function setup() {
    onMount(() => console.log('onMount!'));
  }
</script>

Since the component is still initializing, this is perfectly fine.

It is also not necessary to import the onMount function within the component. As you see in the following example, you can import it in another file; as long as the onMount function is called during component initialization, it is perfectly fine:

// file-a.js
import { onMount } from 'svelte';
export function setup() {
  onMount(() => console.log('onMount!'));
}

In the preceding code snippet, we’ve moved the setup function we defined previously to a new module called file-a.js. Then, in the original Svelte component, rather than defining the setup function, we import it from file-a.js, shown in the following code snippet:

<script>
  import { setup } from './file-a.js';
  setup();
</script>

Since the setup function calls the onMount function, the same rule applies to the setup function too! You can no longer call the setup function outside component initialization.

Which component to register?

Looking at just the setup function, you may be wondering, when you call the onMount function, how does Svelte know which component’s lifecycle you are referring to?

Internally, Svelte keeps track of which component is initializing. When you call the lifecycle functions, it will register your function to the lifecycle of the component that is being initialized.

So, the same setup function can be called within different components and registers the onMount function for different components.

This unlocks the first pattern in this chapter: reusing lifecycle functions.

Reusing lifecycle functions in Svelte components

In the previous section, we learned that we can extract the calling of lifecycle functions into a function and reuse the function in other components.

Let’s look at an example. In this example, after the component is added to the screen for 5 seconds, it will call the showPopup function. I want to reuse this logic of calling showPopup in other components:

<script>
  import { onMount } from 'svelte';
  import { showPopup } from './popup';
  onMount(() => {
    const timeoutId = setTimeout(() => {
      showPopup();
    }, 5000);
    return () => clearTimeout(timeoutId);
  });
</script>

Here, I can extract the logic into a function, showPopupOnMount:

// popup-on-mount.js
import { onMount } from 'svelte';
import { showPopup } from './popup';
export function showPopupOnMount() {
  onMount(() => {
    const timeoutId = setTimeout(() => {
      showPopup();
    }, 5000);
    return () => clearTimeout(timeoutId);
  });
}

And now, I can import this function and reuse it in any component:

<script>
  import { showPopupOnMount } from './popup-on-mount';
  showPopupOnMount();
</script>

You may be wondering, why not only extract the callback function and reuse that instead?

// popup-on-mount.js
import { showPopup } from './popup';
export function showPopupOnMount() {
  const timeoutId = setTimeout(() => {
    showPopup();
  }, 5000);
  return () => clearTimeout(timeoutId);
}

Over here, we extract only setTimeout and clearTimeout logic into showPopupOnMount, and pass the function into onMount:

<script>
  import { onMount } from 'svelte';
  import { showPopupOnMount } from './popup-on-mount';
  onMount(showPopupOnMount);
</script>

In my opinion, the second approach of refactoring and reusing is not as good as the first approach. There are a few pros in extracting the entire calling of the lifecycle functions into a function, as it allows you to do much more than you can otherwise:

  • You can pass in different input parameters to your lifecycle functions.

    Let’s say you wish to allow different components to customize the duration before showing the popup. It is much easier to pass that in this way:

    <script>
      import { showPopupOnMount } from './popup-on-mount';
      showPopupOnMount(2000); // change it to 2s
    </script>
  • You can return values from the function.

    Let’s say you want to return the timeoutId used in the onMount function so that you can cancel it if the user clicks on any button within the component.

    It is near impossible to do so if you just reuse the callback function, as the value returned from the callback function will be used to register for the onDestroy lifecycle function:

    <script>
      import { showPopupOnMount } from './popup-on-mount';
      const timeoutId = showPopupOnMount(2000);
    </script>
    <button on:click={() => clearTimeout(timeoutId)} />

    See how easy it is to implement it to return anything if we write it this way:

    // popup-on-mount.js
    export function showPopupOnMount(duration) {
      let timeoutId;
      onMount(() => {
        timeoutId = setTimeout(() => {
          showPopup();
        }, duration ?? 5000);
        return () => clearTimeout(timeoutId);
      });
      return timeoutId;
    }
  • You can encapsulate more logic along with the lifecycle functions.

    Sometimes, the code in your lifecycle functions callback function does not work in a silo; it interacts with and modifies other variables. To reuse lifecycle functions like this, you must encapsulate those variables and logic into a reusable function.

    To illustrate this, let’s look at a new example.

    Here, I have a counter that starts counting when a component is added to the screen:

    <script>
      import { onMount } from 'svelte';
      let counter = 0;
      onMount(() => {
        const intervalId = setInterval(() => counter++, 1000);
        return () => clearInterval(intervalId);
      });
    </script>
    <span>{counter}</span>

    The counter variable is coupled with the onMount lifecycle functions; to reuse this logic, the counter variable and the onMount function should be extracted together into a reusable function:

    import { writable } from 'svelte/store';
    import { onMount } from 'svelte';
    export function startCounterOnMount() {
      const counter = writable(0);
      onMount(() => {
        const intervalId = setInterval(() => counter.update($counter => $counter + 1), 1000);
        return () => clearInterval(intervalId);
      });
      return counter;
    }

    In this example, we use a writable Svelte store to make the counter variable reactive. We will delve more into Svelte stores in Part 3 of this book.

    For now, all you need to understand is that a Svelte store allows Svelte to track changes in a variable across modules, and you can subscribe to and retrieve the value of the store by prefixing a $ in front of a Svelte store variable. For example, if you have a Svelte store named counter, then to get the value of the Svelte store, you would need to use the $counter variable.

    Now, we can use the startCounterOnMount function in any Svelte component:

    <script>
      import { startCounterOnMount } from './counter';
      const counter = startCounterOnMount();
    </script>
    <span>{$counter}</span>

I hope I’ve convinced you about the pros of extracting the calling of lifecycle functions into a function. Let’s try it out in an example.

Exercise 1 – Update counter

In the following example code, I want to know how many times the component has gone through the update cycle.

Using the fact that every time the component goes through the update cycle, the afterUpdate callback function will be called, I created a counter that will be incremented every time the afterUpdate callback function is called.

To help us measure only the update count of a certain user operation, we have functions to start measuring and stop measuring, so the update counter is only incremented when we are measuring:

<script>
  import { afterUpdate } from 'svelte';
  let updateCount = 0;
  let measuring = false;
  afterUpdate(() => {
    if (measuring) {
      updateCount ++;
    }
  });
  function startMeasuring() {
    updateCount = 0;
    measuring = true;
  }
  function stopMeasuring() {
    measuring = false;
  }
</script>
<button on:click={startMeasuring}>Measure</button>
<button on:click={stopMeasuring}>Stop</button>
<span>Updated {updateCount} times</span>

To reuse all the logic of the counter: – the counting of update cycles and the starting and stopping of the measurement – we should move all of it into a function, which ends up looking like this:

<script>
  import { createUpdateCounter } from './update-counter';
  const { updateCount, startMeasuring, stopMeasuring } = createUpdateCounter();
</script>
<button on:click={startMeasuring}>Measure</button>
<button on:click={stopMeasuring}>Stop</button>
<span>Updated {$updateCount} times</span>

The update counter returns an object that contains the updateCount variable and the startMeasuring and stopMeasuring functions.

The implementation of the createUpdateCounter function is left as an exercise to you, and you can check the answer at https://github.com/PacktPublishing/Real-World-Svelte/tree/main/Chapter01/01-update-counter.

We’ve learned how to extract a lifecycle function and reuse it, so let’s take it up a notch and reuse multiple lifecycle functions in the next pattern: composing lifecycle functions.

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.

Coordinating lifecycle functions across components

As we reuse the same function across components, we can keep track globally of the components that use the same lifecycle function.

Let me show you an example. Here, I would like to keep track of how many components on the screen are using our lifecycle function.

To count the number of components, we can define a module-level variable and update it within our lifecycle function:

import { onMount, onDestroy } from 'svelte';
import { writable } from 'svelte/store';
let counter = writable(0);
export function setupGlobalCounter() {
  onMount(() => counter.update($counter => $counter + 1));
  onDestroy(() => counter.update($counter => $counter - 1));
  return counter;
}

As the counter variable is declared outside the setupGlobalCounter function, the same counter variable instance is used and shared across all the components.

When any component is mounted, it will increment the counter, and any component that is referring to the counter will get updated with the latest counter value.

This pattern is extremely useful when you want to set up a shared communication channel between components and tear it down in onDestroy when the component is being destroyed.

Let’s try to use this technique in our next exercise.

Exercise 2 – Scroll blocker

Usually, when you add a pop-up component onto the screen, you want the document to not be scrollable so that the user focuses on the popup and only scrolls within the popup.

This can be done by setting the overflow CSS property of the body to "hidden".

Write a reusable function used by pop-up components that disables scrolling when the pop-up component is mounted. Restore the initial overflow property value when the pop-up component is destroyed.

Do note that it is possible to have more than one pop-up component mounted on the screen at once, so you should only restore the overflow property value when all the popups are destroyed.

You can check the answer at https://github.com/PacktPublishing/Real-World-Svelte/tree/main/Chapter01/02-scroll-blocker.

Summary

In this chapter, we went through the lifecycles of a Svelte component. We saw the different stages of a component lifecycle and learned when the lifecycle function callbacks will be called.

We also covered the rule of calling lifecycle functions. This helps us to realize the different patterns of reusing and composing lifecycle functions.

In the next chapter, we will start to look at the different patterns for styling and theming a Svelte component.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Create Svelte component lifecycles by styling and theming components as well as managing props and states
  • Leverage actions to build custom events, integrate libraries, and enhance UI elements progressively
  • Explore transitions, write custom transitions, and go through accessibility with transitions in Svelte
  • Purchase of the print or Kindle book includes a free PDF eBook

Description

Svelte has quickly become a popular choice among developers seeking to build fast, responsive, and efficient web applications that are high-performing, scalable, and visually stunning. This book goes beyond the basics to help you thoroughly explore the core concepts that make Svelte stand out among other frameworks. You’ll begin by gaining a clear understanding of lifecycle functions, reusable hooks, and various styling options such as Tailwind CSS and CSS variables. Next, you’ll find out how to effectively manage the state, props, and bindings and explore component patterns for better organization. You’ll also discover how to create patterns using actions, demonstrate custom events, integrate vanilla JS UI libraries, and progressively enhance UI elements. As you advance, you’ll delve into state management with context and stores, implement custom stores, handle complex data, and manage states effectively, along with creating renderless components for specialized functionalities and learning animations with tweened and spring stores. The concluding chapters will help you focus on enhancing UI elements with transitions while covering accessibility considerations. By the end of this book, you’ll be equipped to unlock Svelte's full potential, build exceptional web applications, and deliver performant, responsive, and inclusive user experiences.

Who is this book for?

This book is for experienced web developers looking to enhance their skills and create high-performance web applications. Familiarity with JavaScript, frontend development, and basic Svelte concepts is recommended, making it ideal for professionals and developers who want to master Svelte's advanced features.

What you will learn

  • Master Svelte component development and write efficient Svelte code
  • Implement styling and theming techniques to create visually stunning UIs
  • Create reusable and composable Svelte components for better code organization
  • Understand state management with context and stores for scalable applications
  • Explore different use cases of Svelte stores and Svelte context
  • Utilize tweened and spring stores for complex animations and custom easing
Estimated delivery fee Deliver to Indonesia

Standard delivery 10 - 13 business days

$12.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 01, 2023
Length: 282 pages
Edition : 1st
Language : English
ISBN-13 : 9781804616031
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
Estimated delivery fee Deliver to Indonesia

Standard delivery 10 - 13 business days

$12.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

Product Details

Publication date : Dec 01, 2023
Length: 282 pages
Edition : 1st
Language : English
ISBN-13 : 9781804616031
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 116.96 124.97 8.01 saved
50 Algorithms Every Programmer Should Know
$49.99
SvelteKit Up and Running
$34.99
Real-World Svelte
$31.98 $39.99
Total $ 116.96 124.97 8.01 saved Stars icon

Table of Contents

21 Chapters
Part 1: Writing Svelte Components Chevron down icon Chevron up icon
Chapter 1: Lifecycles in Svelte Chevron down icon Chevron up icon
Chapter 2: Implementing Styling and Theming Chevron down icon Chevron up icon
Chapter 3: Managing Props and State Chevron down icon Chevron up icon
Chapter 4: Composing Components Chevron down icon Chevron up icon
Part 2: Actions Chevron down icon Chevron up icon
Chapter 5: Custom Events with Actions Chevron down icon Chevron up icon
Chapter 6: Integrating Libraries with Actions Chevron down icon Chevron up icon
Chapter 7: Progressive Enhancement with Actions Chevron down icon Chevron up icon
Part 3: Context and Stores Chevron down icon Chevron up icon
Chapter 8: Context versus Stores Chevron down icon Chevron up icon
Chapter 9: Implementing Custom Stores Chevron down icon Chevron up icon
Chapter 10: State Management with Svelte Stores Chevron down icon Chevron up icon
Chapter 11: Renderless Components Chevron down icon Chevron up icon
Chapter 12: Stores and Animations Chevron down icon Chevron up icon
Part 4: Transitions Chevron down icon Chevron up icon
Chapter 13: Using Transitions Chevron down icon Chevron up icon
Chapter 14: Exploring Custom Transitions Chevron down icon Chevron up icon
Chapter 15: Accessibility with Transitions Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.7
(3 Ratings)
5 star 66.7%
4 star 33.3%
3 star 0%
2 star 0%
1 star 0%
Daniel Pointecker Jan 19, 2024
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I'm not finished but for what i read its a good book with useful tips i did not get from the official docs.
Feefo Verified review Feefo image
Steven Hagene Feb 5, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book has really helped me with my understanding of Svelte and has helped make me much more proficient with my code. I would like to thank the author for the work that he has done with this book.
Feefo Verified review Feefo image
Danilo Campos Jan 19, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Amazing, clear survey of everything you can do with Svelte, packaged much more consumable than the official documentation. This is the perfect companion for those who want to learn the best web development framework out there.
Feefo Verified review Feefo image
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela