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 ponents, and I'm wondering if this would be considered an anti-pattern or if it could result in unwanted issues?
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 ponents, and I'm wondering if this would be considered an anti-pattern or if it could result in unwanted issues?
Share Improve this question asked Feb 27, 2020 at 21:24 Mike MaliszMike Malisz 1032 silver badges8 bronze badges 2- 1 no, that's fine. – Jonas Wilms Commented Feb 27, 2020 at 21:27
-
2
Side note: you could specify the object properties as dependencies instead of the entire object. E.g.
[person.name]
and[person.age]
– Andy Mardell Commented Feb 27, 2020 at 21:31
2 Answers
Reset to default 5You 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])