What is the Observer Pattern?

The Observer pattern lets an object (the subject) keep a list of dependents (observers) and notify them automatically when its state changes, so they stay in sync without the subject knowing what they do.

Structure

  • Subject: holds state, subscribe(observer), unsubscribe(observer), notify().
  • Observers: callbacks or objects with an update method.
  • subscribe usually returns an unsubscribe function, which makes cleanup easy.

Where you meet it

  • DOM events (addEventListener is observer registration).
  • State libraries: Redux store.subscribe, Zustand, MobX, signals.
  • React's useSyncExternalStore, which subscribes components to any external store.
  • IntersectionObserver, MutationObserver, ResizeObserver.
  • RxJS observables, WebSocket message handlers, Node's EventEmitter.

Observer vs Pub/Sub

In Observer, observers subscribe directly to the subject. In Pub/Sub, publishers and subscribers communicate through a message broker or event bus using topics, and do not know about each other.

Pitfalls

  • Memory leaks when observers forget to unsubscribe.
  • Notification storms: many updates in a row trigger many notifications. Batch them (for example with a microtask).
  • Order dependence between observers, and an observer throwing an error that stops others from being notified (wrap each call).
  • Changing the observer list while notifying: iterate over a copy.

Code example

js
1class Observable {
2 #state;
3 #observers = new Set();
4 constructor(initial) {
5 this.#state = initial;
6 }
7 get state() {
8 return this.#state;
9 }
10 #call(observer) {
11 try {
12 observer(this.#state);
13 } catch (e) {
14 console.log("observer failed:", e.message); // one bad observer doesn't stop others
15 }
16 }
17 subscribe(observer) {
18 this.#observers.add(observer);
19 this.#call(observer); // send the current value immediately
20 return () => this.#observers.delete(observer); // unsubscribe function
21 }
22 set(updater) {
23 this.#state = typeof updater === "function" ? updater(this.#state) : updater;
24 for (const observer of [...this.#observers]) this.#call(observer); // copy: safe if the list changes
25 }
26}
27
28const cart = new Observable({ items: 0 });
29const badge = [];
30const totals = [];
31
32const unsubscribeBadge = cart.subscribe((s) => badge.push(`badge: ${s.items}`));
33cart.subscribe((s) => totals.push(`total: $${s.items * 10}`));
34cart.subscribe(() => {
35 throw new Error("broken widget");
36});
37
38cart.set((s) => ({ items: s.items + 1 }));
39unsubscribeBadge();
40cart.set((s) => ({ items: s.items + 2 }));
41
42console.log(badge); // ["badge: 0", "badge: 1"] - stopped after unsubscribing
43console.log(totals); // ["total: $0", "total: $10", "total: $30"]

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app