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);
}

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.

Further reading

Problem with a question

Design Patterns · Middle · question 2

Test yourself

Take the Design Patterns · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz