简体   繁体   中英

Multiple React effect hooks for the same dependency

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?

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM