DEV Community

Discussion on: 1 year with React Hooks - Biggest lesson learned

Collapse
 
miketalbot profile image
Mike Talbot ⭐ • Edited

Yeah using useEffect as a watch isn't really what it's for. Certainly not when regarding the internal logic of a component.

Your component is trying to reuse logic for two things and React isn't doing any magic to help you - so you could just fix your problem by setting the response to [] inside your toggle function as this is the moment where the logic breaks - or you can make the output self-contained so all the data is together (as you do in your conclusion).

As I'm sure you know, you can do state management using external libraries and React is pretty much only worried about the view - so Redux or a dozen other things including my library will help. In the case of mine actually providing you with immediate events when a value changes - basically giving you a watch. React doesn't have this under the covers - which certainly makes the learning experience an interesting one!

Here's a version that forces that explicit update for instance: