Browser Storage and State ManagementLesson 5.4
Building a simple client-side state manager with localStorage
state management pattern, getState, setState, subscribers, pub-sub, localStorage sync, JSON serialization
Client-Side State Manager
For small apps without a framework, a simple pub-sub state manager gives you predictable data flow without external libraries.
const Store = (() => {
const KEY = 'app-state';
const subscribers = [];
function getState() {
const raw = localStorage.getItem(KEY);
return raw ? JSON.parse(raw) : { todos: [], theme: 'light' };
}
function setState(partial) {
const next = { ...getState(), ...partial };
localStorage.setItem(KEY, JSON.stringify(next));
subscribers.forEach(fn => fn(next));
}
function subscribe(fn) {
subscribers.push(fn);
return () => subscribers.splice(subscribers.indexOf(fn), 1);
}
return { getState, setState, subscribe };
})();
// Usage
Store.subscribe(state => renderApp(state));
Store.setState({ theme: 'dark' });Call the returned unsubscribe function when a component is removed from the DOM to prevent memory leaks.
