skip to Main Content

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.

  1. I have to fetch data from server when component loads? what should I use instead of useEffect?
  2. I have to perform some operation on state change? how can i detect state change and perform that action..
  3. 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


  1. 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,

    1. You can use useQuery, it is much more refined for this particular use-case.
      https://tanstack.com/query/v4/docs/react/reference/useQuery

    2. You can use useEffect. It is perfectly alright.

    3. 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 where useEffect 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

    Login or Signup to reply.
  2. Sometimes in rare cases the useEffect is needed and for examples you mentioned above:

    1. For fetching data using react-query will be much better https://www.npmjs.com/package/react-query
    2. You can avoid using a useEffect 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.. } />
    3. This is a bit similar to the point number 2 answer

    When you using a useEffect always ask yourself if you really need it and try to see other possibilities.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search