Design Patterns · Middle · Question 2 of 75
Why does subscribe in an Observer implementation usually return an unsubscribe function?
function subscribe(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
}- ✓Correct answer: So the subscriber can easily unsubscribe and avoid a memory leak
- 2So the subscription fires only once and then removes itself
- 3So the subject can call the subscriber synchronously, without the event loop
Explanation
The returned function fits neatly into useEffect cleanup: useEffect(() => store.subscribe(fn), []). Without unsubscribing, the subject keeps references to callbacks of unmounted components - a leak and extra calls. Redux, Zustand and useSyncExternalStore work this way.