DEV Community

Joanna Otmianowska
Joanna Otmianowska

Posted on

Multiple or one useEffect?

When I started working with React hooks, I had a tendency to put everything that was based on component change into one useEffect. I was used to put it into lifecycle methods like componentDidMount, componentDidUpdate or componentWillUnmount. It was natural for me that I need to show my component what to do on the particular stage - so something happens with mounting, something with unmounting etc. I based the logic on the component lifecycle, not on what this logic does. Therefore I ended up having completely unrelated logic in one useEffect just because I wanted all of that stuff to happen with component mount. Fortunately, I quickly realised that I was wrong.

You can have multiple useEffects in your code and this is completely fine! As hooks docs say, you should separate concerns. Multiple hooks rule also applies to useState - you can have multiple useState in one component to separate different part of the state, you don't have to build one complicated state object.

Going back to useEffect - reading the docs I linked earlier made me change my approach to managing component behaviour using hooks. Right now I always ask myself first if things that I do in one useEffect are really connected. If not, I try to extract the logic to another useEffect. Thanks to that I can easily see what happens to the code and I can avoid running some code with no reason (e.g. maybe something is needed to be done only with component first mount).

However, I try to be mindful and not simply put every single thing in a separate useEffect. If one data relies on another, I would probably fetch it in one useEffect to make sure that I have both things in place on time. The same goes with loading - I put changes related to loaders next to the things that caused them. This way I can see when the loader state is changing and what's causing that.

Did you also have problems with using multiple useEffect or did you find it easy from the beginning? Let's talk!

Discussion (0)