javascript / expert
Snippet
Reactive State Persistence with Signal Effects and Cleanup
The effect() function provides an onCleanup callback that is essential for managing side effects. This snippet demonstrates how to debounce persistence logic to localStorage, ensuring that the cleanup function cancels pending timeouts if the signal changes rapidly.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
export class PreferencesService {theme = signal<'dark' | 'light'>(localStorage.getItem('theme') as any || 'light');constructor() {effect((onCleanup) => {const currentTheme = this.theme();const timeout = setTimeout(() => {localStorage.setItem('theme', currentTheme);}, 1000);onCleanup(() => clearTimeout(timeout));});}}
angular
Breakdown
1
effect((onCleanup) => { ... })
Registers a reactive side effect that tracks signal dependencies automatically.
2
const timeout = setTimeout(...)
Implements a simple debounce to avoid excessive disk I/O.
3
onCleanup(() => clearTimeout(timeout))
Cleans up the previous side effect before the next one runs or the service is destroyed.