javascript / expert
Snippet
Bitwise State Management for High-Performance Flags
When managing numerous boolean states, using bitwise operators to pack flags into a single integer reduces reactive overhead. Svelte only needs to track one number instead of multiple boolean runes, optimizing memory and update cycles for complex components.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
const FLAG_VISIBLE = 1 << 0; // 1const FLAG_LOADING = 1 << 1; // 2const FLAG_ERROR = 1 << 2; // 4let state = $state(0);function toggleLoading(on) {if (on) state |= FLAG_LOADING;else state &= ~FLAG_LOADING;}const isLoading = $derived((state & FLAG_LOADING) !== 0);
svelte
Breakdown
1
state |= FLAG_LOADING;
Uses the bitwise OR operator to set the loading flag bit to 1.
2
state &= ~FLAG_LOADING;
Uses bitwise AND and NOT to clear the loading flag bit back to 0.