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

Managing Props and State

In the world of web development, managing data effectively is crucial. Whether it’s the information that flows between components or the internal state of a component, proper data management is the backbone of a functional and responsive web application.

In this chapter, we will delve into the core concepts of managing props and state within a Svelte application. First, we’ll clarify what props and states in Svelte are, laying the groundwork for understanding more advanced topics. We then explore the concept of bindings, a feature in Svelte for keeping state and element values or component props in sync.

We’ll then explore data flow within components, highlighting the differences between one-way data flow and two-way data flow and why they matter. Moving on, we’ll discuss how to derive state from props using Svelte’s reactive declarations. To conclude, we’ll offer tips for managing complex derived states and explain...

Technical requirements

You can find all the code samples used in this chapter on GitHub at https://github.com/PacktPublishing/Real-World-Svelte/tree/main/Chapter03

Defining props and state

In Svelte, both props and state are used to manage data within components. Props are a way to pass data from a parent component to a child component. This makes the child component flexible and reusable, as it can get different data from the parent as needed.

On the other hand, state is data that is initialized and managed internally within a component, unlike props, which are received from an external source. State allows a component to be self-contained and modular.

Defining props

Let’s start with props. Props in Svelte are defined using the export keyword. When you export a variable in a Svelte component, it becomes a prop that you can pass data to from a parent component.

Here is a simple example:

<!-- file: Child.svelte -->
<script>
  export let message;
</script>
<h1>{message}</h1>

In the preceding code snippet, we defined a Svelte component in a file named Child.svelte. In the Svelte component...

Understanding bindings

Bindings in Svelte allow you to keep the value of a component’s state in sync with the value of an <input /> element. If the state changes, the input updates; conversely, if the input changes, the state updates as well.

The following code snippet is an example of creating a binding in Svelte:

<script>
  let name = "John";
</script>
<input bind:value={name} />

Bindings are created through the bind: directive. In the preceding code snippet, the input element’s value is bound to the name variable. When you type in the input, the name variable will update automatically. Conversely, when you change the value of the name variable, the input element’s value will also automatically update.

As demonstrated, bindings create a two-way data flow, enabling data changes to propagate from the element to the component state, and from the component state into the element.

The previous example demonstrates...

One-way versus two-way data flow

When you pass data from one component to another component either through props or binding, data flows from one component to another component. The term data flow refers to how data is passed or transmitted between components or elements within a web application.

Understanding data flow is important when designing an application’s architecture, as it helps to establish clear lines of communication between components and determine how information is shared and updated throughout the system.

Data flow can be unidirectional (one-way) or bidirectional (two-way), depending on how data is transferred between components.

In one-way data flow, data moves in a single direction, from a parent to a child component, or from a component to a DOM element. This unidirectional flow is achieved through component props or DOM element attributes.

For example, consider the following code snippets featuring two components, component A and component B...

Deriving states from props with a reactive declaration

It’s common in Svelte to create new state variables based on the values of props.

For instance, a <DateLabel /> component might accept a date value as a prop and display a formatted date inside a <label> element. To use the <DateLabel> component, you might write the following:

<DateLabel date={new Date(2023,5,5)} />

To display the date as formatted text, you could first define a variable named label, deriving its value from the date prop:

<!-- filename: DateLabel.svelte -->
<script>
  export let date;
  // Deriving the 'label' variable from the 'date' prop
  let label = date.toLocaleDateString();
</script>
<label>{label}</label>

In this code snippet, we defined a variable called label and derived its value from the date prop using the toLocaleDateString() method. This variable is then used inside a <label...

Managing complex derived states

As your Svelte application grows more complex, it will likely involve a greater number of interconnected components with multiple props and derived states. When dealing with this complexity, tracking updates and changes can become a complex task. Each prop or state change can affect other parts of your component, making it challenging to manage and predict how your component will behave.

To make this easier, here are some guidelines to consider:

  • Maintain one-way data flow for derived states

    While it’s possible to derive state from props and other states, it’s crucial to maintain a one-way data flow to simplify both debugging and understanding. Consider the following Svelte example:

    <script>
      export let valueA;
      export let valueB;
      $: valueC = valueA + 5;
      $: valueD = valueB + valueC;
      $: valueC = Math.min(valueC, valueD / 2);
    </script>

    This code snippet won’...

Updating props using derived states

In an attempt to synchronize the value prop with changes to the input bound to triple, one might be tempted to add another reactive declaration. This declaration would update the value prop to be one-third of triple whenever triple changes. Here is the proposed modification:

<script>
  export let value;
  $: double = value * 2;
  $: triple = value * 3;
  $: value = double / 2;
  $: value = triple / 3;
</script>
<input bind:value={double} type="number" />
<input bind:value={triple} type="number" />

As we discussed earlier, it’s best practice to maintain a one-way data flow for derived states to simplify debugging and data management. Indeed, the Svelte compiler flags the preceding code snippet for cyclical dependencies. This is because double is derived from value, and value is in turn dependent on double.

However, Svelte’s compiler...

Summary

Understanding how to handle props and state effectively is crucial for creating robust Svelte apps. This chapter has shown you how Svelte uses props, bindings, and reactive declarations to facilitate data passing and state changes across components.

It’s crucial to keep an eye on data flow within a component. Having a unified and organized data flow makes the code easier to follow and debug. Good data management paves the way for building more intricate and dynamic apps with ease.

In the next chapter, we’ll explore how to compose Svelte components to construct more complex applications.

lock icon
The rest of the chapter is locked
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 €14.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