did you know that you can conditionally exit an effect?
this is useful if you want a subscription to only stay active while some condition is true, and to stay removed while that condition is false.
a bit mindbending, but so it is with react!
It is a callback *function*. It is just a function. `return` is how you exit a function.
Not sure that this is "mind bending". And this is how JavaScript works, not so much about React.
it is mindbending in the sense that when trying to implement the described behavior, simply returning is not an obvious solution.
this is because imperatively it’s usually implemented like
if (!wasActive && isActive) {
subscribe()
} else if (wasActive && !isActive) {
unsubscribe()
}
however, React effects don’t provide a way to read previous values of state so it’s unclear where to stick this code
the mindbending moment is realizing that by exiting early, you’ll let the “previous iteration” of the effect clean up for itself (unsubscribing), while the “next iteration” is a noop
to put this more generally, this is about early exits in reactive code (which re-runs over and over when the variables that it closes over change)
in non-reactive code, the intuition is that early exit “does nothing” whereas you wanted to unsubscribe. but in reactive code, it does unsubscribe!
Nov 2, 2024 23:50