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 store1function createStore(initialState) { // Private state variable2 let state = initialState; // Set of subscriber functions3 const listeners = new Set();4 5 return { // Return current state6 getState: () => state, // Update state and notify listeners7 setState: (updater) => { // If updater is a function, call it with the old state; otherwise use it as the new state8 state = typeof updater === "function" ? updater(state) : updater; // Notify all subscribers with new state9 listeners.forEach(fn => fn(state));10 }, // Add subscriber, return unsubscribe function11 subscribe: (fn) => {12 listeners.add(fn); // Return cleanup function13 return () => listeners.delete(fn);14 }15 };16}17 // Create store with initial state18const store = createStore({ count: 0 });// Subscribe and save unsubscribe function19const 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 updates23unsubscribe();// This update won't log (unsubscribed)24store.setState({ count: 100 });Output
Count: 1 Count: 2
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