What is the good practice to use React.JS useEffect hook for multiple states

Viewed 538

What is the best practice to use React.JS useEffect hook when listening for multiple states change

first:

  useEffect(() => {
    if ( first ) {
      // do the stuff for first state changes
    }

    if ( second ) {
      // do the stuff for second state changes
    }
  })

second:

  useEffect(() => {
  // do the stuff for first state changes 
  }, [first])



  useEffect(() => {
    // do the stuff for second state changes 
  }, [second])

and what are the pros and cons between these two methods?

2 Answers

It depends on the situation, but for most cases you should use separate useEffect for each use case.

If you do:

  useEffect(() => {
    if ( first ) {
      // do the stuff for first state changes
    }

    if ( second ) {
      // do the stuff for second state changes
    }
  }, [first, second])

This useEffect will run every time first and second changes. You should ask yourself, do I need to check first and update it when second changes, and vice versa. If that is the case, you should combine them into a single useEffect, although I would personally not use separate state variables for that.

In the second case, you isolate the changes.

  useEffect(() => {
  // do the stuff for first state changes 
  }, [first])


  useEffect(() => {
    // do the stuff for second state changes 
  }, [second])

When first changes, you are going to handle the state changes for first and the same thing for second. To avoid any side effects, you should try to separate the useEffect calls.

I would vote for the 2nd option for a couple of reasons:

  • Reduce unnecessary checks when combining multiple state changes
  • The First option always get trigger every state/props changes
  • Taking more control when to run which useEffect.
  • Separate of concern

And React actually encourage us to do that.

But it entirely depends on your case

Related