Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
682 views
in Technique[技术] by (71.8m points)

reactjs - Should I use one or many useEffect in component?

I have some side effects to apply and want to know how to organize them:

  • as a single useEffect
  • or several useEffects

What's better in terms of performance and architecture?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The pattern that you need to follow depends on your useCase.

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 benefits

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

Second: There may be a case where you need to trigger an API call or some other side-effect when any of the state or props change amongst a set. In such a case a single useEffect with the relevant values to monitor should be a good idea

useEffect(() => {
    // side effect here on change of any of props.x or stateY
}, [props.x, stateY])

Third: A third case in when you need to take different actions on change of different values. In such a case, separate out relevant comparisons into different useEffects

useEffect(() => {
   // some side-effect on change of props.x
}, [props.x])

useEffect(() => {
   // another side-effect on change of stateX or stateY 
}, [stateX, stateY])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...