React @react.dev · Nov 1

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!

403 likes 11 replies

?

Replies

dimitrios · Nov 2

Just don't return null. Undefined works nicely.

Jacek Wojtalewicz · Dec 5

Programmers delight

Chip Osur · Nov 2

Copilot actually suggested this pattern to me and I have used it a few times since

glneto · Nov 3

doesn't play well with this lint rule though eslint.org/docs/latest/... we had to drop it from our lint config especially because of those kind of useEffecys but tbh I don't miss it 🙏

Alex Machin · Nov 1

Huh didn't realize you could just bail out of a useEffect interesting.

Seb ⚛️ ThisWeekInReact.com · Nov 7

Shared a recent blog article on this from @robinmalfait.com in the newsletter: robinmalfait.com/blog/conditi...

Greg Fenton · Nov 1

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.

Alex Kates · Nov 2

i do this so much... "guard clauses" are goat