0 day streak
javascript / expert
Snippet

Advanced Custom Store with Memoized Invalidation

Custom Svelte stores can be optimized by overriding the default set/update behavior. By implementing a memoized comparison function, we prevent unnecessary reactive triggers and downstream component re-renders when the data structure hasn't effectively changed, which is critical for complex nested objects.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { writable } from 'svelte/store';
export function createMemoStore(initialValue, compareFn = (a, b) => JSON.stringify(a) === JSON.stringify(b)) {
const { subscribe, set, update } = writable(initialValue);
let currentValue = initialValue;
return {
subscribe,
set: (newValue) => {
if (!compareFn(currentValue, newValue)) {
currentValue = newValue;
set(newValue);
}
},
update: (fn) => {
const newValue = fn(currentValue);
if (!compareFn(currentValue, newValue)) {
currentValue = newValue;
set(newValue);
}
}
};
}
svelte
Breakdown
1
compareFn = (a, b) => ...
Allows defining custom equality logic, such as deep comparison or ID-based checks.
2
if (!compareFn(currentValue, newValue))
Short-circuits the store notification if the new value is functionally identical to the current one.