Multiple React effect hooks for the same dependency

Viewed 1500

Let's say I have an effect hook with a Person dependency that follows the schema Person: {name: string, age: number}. My effect hook for this Person dependency currently looks like this:

useEffect(() => {
  if (person.name === 'Mike') {
    doSomething()
  }

  if (person.age > 21) {
    somethingElse()
  }
}, [person])

Would it be valid code to separate this logic into their own effect hooks with the same dependencies:

// effect that handles any logic for a person's name
useEffect(() => {
  if (person.name === 'Mike') {
    doSomething()
  }
}, [person])

// effect that handles any logic for a person's age
useEffect(() => {
  if (person.age > 21) {
    somethingElse()
  }
}, [person])

I'm trying to separate unrelated code from each other in some of my components, and I'm wondering if this would be considered an anti-pattern or if it could result in unwanted issues?

2 Answers

You are correct. Although, I would check person properties on each individual effect call separately. Check the react docs here for a good example. ( I really dislike when others are answering and I'm still typing...)

 // effect that handles any logic for a person's name
useEffect(() => {
  if (person.name === 'Mike') {
    doSomething()
  }
}, [person.name])

// effect that handles any logic for a person's age
useEffect(() => {
  if (person.age > 21) {
    somethingElse()
  }
}, [person.age])

While it is acceptable to write code in this fashion, you might want to run the effects on what they're actually concerned with. ie

// effect that handles any logic for a person's name
useEffect(() => {
  if (person.name === 'Mike') {
    doSomething()
  }
}, [person.name])

// effect that handles any logic for a person's age
useEffect(() => {
  if (person.age > 21) {
    somethingElse()
  }
}, [person.age])
Related