Reactive Store Pattern in JavaScript

Level 5594 keystrokes

Reactive stores notify subscribers automatically when state changes, enabling reactive UIs.

JavaScript code

// Factory function to create a reactive store
1function createStore(initialState) {
// Private state variable
2 let state = initialState;
// Set of subscriber functions
3 const listeners = new Set();
4
5 return {
// Return current state
6 getState: () => state,
// Update state and notify listeners
7 setState: (updater) => {
// If updater is a function, call it with the old state; otherwise use it as the new state
8 state = typeof updater === "function" ? updater(state) : updater;
// Notify all subscribers with new state
9 listeners.forEach(fn => fn(state));
10 },
// Add subscriber, return unsubscribe function
11 subscribe: (fn) => {
12 listeners.add(fn);
// Return cleanup function
13 return () => listeners.delete(fn);
14 }
15 };
16}
17
// Create store with initial state
18const store = createStore({ count: 0 });
// Subscribe and save unsubscribe function
19const unsubscribe = store.subscribe(s => console.log("Count:", s.count));
20
// Update state (triggers subscriber)
21store.setState(s => ({ count: s.count + 1 }));
22store.setState(s => ({ count: s.count + 1 }));
// Unsubscribe from updates
23unsubscribe();
// This update won't log (unsubscribed)
24store.setState({ count: 100 });

Output

Count: 1
Count: 2
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • (× 20
  • )× 20
  • =× 16
  • ;× 13
  • .× 11
  • :× 9
  • {× 8
  • }× 8
  • >× 8
  • "× 4

More JavaScript examples at level 5

← JavaScript typing practice