Stores + Svelte

Vanilla JS


<html>
<body>
    <h1>Count: <span id="count">0</span></h1> 
    <button type="button" id="increment">+</button>
    <script>
        let count = 0;
        const currentNode = document.getElementById('count')
        document.getElementById('increment').addEventListener('click', () => {
            count++;
            currentNode.innerText = count;
        })
    </script>
</body>
</html>

React

export default function App() {
    const [count, setCount] = useState(0);

    return (
        <>
            <h1>Count: {count}</h1>
            <button onClick={() => {
                setCount(count + 1);
            }}>+</button>
        </>
    )
}

Svelte

<script>
  let count = 0;
</script>
<h1>Count: {count}</h1>
<button onClick={() => {
    count++
}}>+</button>

Imperative

Declarative

VanillaJS

React

Svelte

Patrick Hultquist

Developer & DX at Monogram

Things go wrong when we try to update data

React

                
setName("Just changed my name");
db.user.update({;
    name: "Just changed my name"
});
            
        
                
// Update props so save button is disabled
props.user.name = "Just changed my name";
        

Svelte

                
<button 
    on:click={() => {
        count++
        updateCountInDb(count)
    }}
/>
            
                
$: updateCountInDb(count)
            

...and things go wrong when using realtime updates

React

                
const [count, setCount] = useState(0)
useEffect(() => {
    let unsubscribe = thing.onChange((newCount) => {
        setCount(newCount)
    })

    return unsubscribe
}, [])

const onButtonClick = () => {
    setCount(count++);
    updateCountInDb(count++);
};

return <button onClick={onButtonClick} />

            
        

Svelte

                
onMount(() => {
    return thing.onChange((newCount) => {
        count = newCount
    })
})

<button 
    on:click={() => {
        count++
        updateCountInDb(count)
    }}
/>
            
                
$: updateCountInDb(count)
            

We're not declarative when we update state.

Intuitive code at Linear
 
user.name = "Just changed my name"; 
user.save();
            
In Svelte
 
$user.name = "Just changed my name"; 
user.save();
            

patrick.app/autostore

Let's see it

Where stores shine

  • Large applications
  • Accessing pieces of data across the app
  • Creating real-time apps

Use cases for Stores

  • Keep signed in user data in a store
  • Track a URL param using the page store
  • Reducing expensive calculations, like useMemo() in React using a derived store
  • Put realtime data in a store and have it live update
  • Using svelte-persistent-store to store user appearance preference
  • Store the user's shopping cart in a store in an E-Commerce site

The concept of an observable isn't new. But the syntax is.

A simple modal with stores

Are we going back to global variables?

wiki.c2.com/?GlobalVariablesAreBad

On bundle sizes

~1kb