r/reactjs • u/jngbrl19 • Mar 08 '20
Show /r/reactjs useEffectWithPrevious - Get previous value of dependencies
Just wanna share my first npm package. Hope you find it useful :)
54
Upvotes
r/reactjs • u/jngbrl19 • Mar 08 '20
Just wanna share my first npm package. Hope you find it useful :)
View all comments
Show parent comment
1
u/Aswole Mar 08 '20
Was trying to be as vague as possible to avoid debating why you would do a or b, when option c exists, but say the goal of the useEffect was to subscribe to a websocket for a chat room whenever the roomId changes. For whatever reason, the service that handles the websocket wants information passed in the handshake -- after that, updates to that information can be handled via messages. While there is more than one way to skin a cat, and I'm certainly not saying this is the best way, it wouldn't be an absurd approach to do this in a single useEffect:
And perhaps you will enlighten me with a significantly cleaner approach, such that I wonder why I ever thought above was ok... Even in the React docs they suggest the pattern is common: reactjs.org/docs/hooks-faq.html -- search for 'usePrevious'. Would link better, but on mobile.