DEV Community

Cover image for Understanding Svelte's $: (dollar label) syntax
Saurabh Sharma
Saurabh Sharma

Posted on • Updated on • Originally published at itsjzt.com

Understanding Svelte's $: (dollar label) syntax

In the long list of cool features of svelte, The one which I use more often is this dollar label thing. Initially, it looked strange to me but later I realized it is a valid javascript syntax. You can use it for doing side effects like useEffect of React, there is also a syntactic sugar way of declaring computed properties.

  1. Doing side effects on state change

Let's say we have a messaging app. You need to change the title when a new unread message comes and you need to update title when the message is read. Traditionally, we will make a function which will update the title and use that function in both places (1. where we are getting new messages from server 2. event listener on user clicking mark as read) but with the svelte's approach we can do this

$: {
    let unreadMessages = messages.filter(m => m.read === false);
    document.title = `${unreadMessages.length} unread messages`;
}
Enter fullscreen mode Exit fullscreen mode

with this approach, we can just change the value of messages in both the places (1. where we are getting new messages from server 2. event listener on user reading the message) and it will be changed in the title. One thing to notice is unlike useEffect of React you don't have to explicitly write the dependencies of this block. The component would be something like this

  1. Computed properties

A computed property is one that will be recalculated if the property it dependents on changes.

Let's say we get another requirement, we also need to show the numbers of unread messages to users above the message list. Since we already have the list of unread messages, we can copy the same logic in the template to show the unread messages or we can do this.

$: unreadMessages = messages.filter(m => m.read === false);
$: {
    document.title = `${unreadMessages.length} unread messages`;
}
Enter fullscreen mode Exit fullscreen mode

here we declared a computed property (unreadMessages). Essentially unreadMessage is a variable that will be recalculated if messages property change. Now we can use this unreadMessages array in the template to show numbers of unread messages.

Top comments (2)

Collapse
 
vikbert profile image
Xun Zhou

the dollar label is actually similar to the react: useEffect(() => {}, [my_variable]); the code in the dollar block will be run:

  • if rerendered
  • if the state variable "my_variable" is changed
Collapse
 
vikbert profile image
Xun Zhou

thx for the nice example