I am hearing term "Avoid using useEffect()
in your react app".
I tried to look for the answers but could not find anything which answers specifically what should I use instead of useEffect?
For example consider below cases.
- I have to fetch data from server when component loads? what should I use instead of useEffect?
- I have to perform some operation on state change? how can i detect state change and perform that action..
- I have 2 components say header and body both sharing a global state… lets say header has a dropdown and I have to perform some operation in body component when that dropdown value changes…. how can I capture the change in state in body component?
How can I avoid using useEffect or am I asking wrong question? perhaps I should ask what is the right way to use useEffect?
2
Answers
Using
useEffect
is perfectly alright. Although, you need to take care of dependencies and make sure it isn’t called unnecessarily.Going through your cases one by one,
You can use
useQuery
, it is much more refined for this particular use-case.https://tanstack.com/query/v4/docs/react/reference/useQuery
You can use
useEffect
. It is perfectly alright.For this case, using state management libraries would be better, example would be
zustand
,redux
, etc.All the mentioned libraries, make your life easier and less prone to errors. However, that doesn’t mean they replace
useEffect
. There are infinite cases whereuseEffect
can and should be used.For the last question, how to properly use
useEffect
I would suggest going through React documentation. They are pretty niche.https://react.dev/reference/react/useEffect
Sometimes in rare cases the
useEffect
is needed and for examples you mentioned above:react-query
will be much better https://www.npmjs.com/package/react-queryuseEffect
by going to the action where the change event is happening and doing the operation directly there. example<input name="firstName" onChange={...the change event is happening here.. } />
When you using a
useEffect
always ask yourself if you really need it and try to see other possibilities.