patternreactCritical
In general is it better to use one or many useEffect hooks in a single component?
Viewed 0 times
hookssingleuseonebettercomponentmanygeneraluseeffect
Problem
I have some side effects to apply in my react component and want to know how to organize them:
Which is better in terms of performance and architecture?
- as a single useEffect
- or several useEffects
Which is better in terms of performance and architecture?
Solution
The pattern that you need to follow depends on your use case.
First: You might have a situation where you need to add event listener during the initial mount and clean them up at unmount and another case where a particular listener needs to be cleaned up and re-added on a prop change.
In such a case, using two different
Second: You need to trigger an API call or some other side-effect when any of the state or props change from a defined set. In such a case a single
Third: You need separate side-effect for different sets of changes. In such a case, separate out relevant side-effects into different
First: You might have a situation where you need to add event listener during the initial mount and clean them up at unmount and another case where a particular listener needs to be cleaned up and re-added on a prop change.
In such a case, using two different
useEffect is better to keep the relevant logic together as well as having performance benefitsuseEffect(() => {
// adding event listeners on mount here
return () => {
// cleaning up the listeners here
}
}, []);
useEffect(() => {
// adding listeners everytime props.x changes
return () => {
// removing the listener when props.x changes
}
}, [props.x])Second: You need to trigger an API call or some other side-effect when any of the state or props change from a defined set. In such a case a single
useEffect with the relevant dependencies to monitor would be betteruseEffect(() => {
// side effect here on change of any of props.x or stateY
}, [props.x, stateY])Third: You need separate side-effect for different sets of changes. In such a case, separate out relevant side-effects into different
useEffectsuseEffect(() => {
// some side-effect on change of props.x
}, [props.x])
useEffect(() => {
// another side-effect on change of stateX or stateY
}, [stateX, stateY])Code Snippets
useEffect(() => {
// adding event listeners on mount here
return () => {
// cleaning up the listeners here
}
}, []);
useEffect(() => {
// adding listeners everytime props.x changes
return () => {
// removing the listener when props.x changes
}
}, [props.x])useEffect(() => {
// side effect here on change of any of props.x or stateY
}, [props.x, stateY])useEffect(() => {
// some side-effect on change of props.x
}, [props.x])
useEffect(() => {
// another side-effect on change of stateX or stateY
}, [stateX, stateY])Context
Stack Overflow Q#54002792, score: 448
Revisions (0)
No revisions yet.