javascript - Does using multiple useEffects in one component have any side effects? - Stack Overflow

I used three useEffect to control different states and addingremoving event listeners. But I'm no

I used three useEffect to control different states and adding/removing event listeners. But I'm not sure that is a best practice or not?

 useEffect(() => {
    window.addEventListener('keydown', keyPressHandle)
    return () => {
      window.removeEventListener('keydown', keyPressHandle)
    }
  }, [])

  useEffect(() => {
    // do sth on state_one
  }, [state_one])

  useEffect(() => {
    // do sth on state_two
  }, [state_two])

I used three useEffect to control different states and adding/removing event listeners. But I'm not sure that is a best practice or not?

 useEffect(() => {
    window.addEventListener('keydown', keyPressHandle)
    return () => {
      window.removeEventListener('keydown', keyPressHandle)
    }
  }, [])

  useEffect(() => {
    // do sth on state_one
  }, [state_one])

  useEffect(() => {
    // do sth on state_two
  }, [state_two])

Share Improve this question asked Sep 6, 2021 at 14:41 curlybomcurlybom 851 silver badge7 bronze badges 1
  • It is the best practice indeed, there are no side effect, the only thing to remember is that they are executed in the order they were declared. – Anthony Raymond Commented Sep 6, 2021 at 14:51
Add a ment  | 

2 Answers 2

Reset to default 5

Yes, this is a best practice and Reactjs also remends it

Tip: Use Multiple Effects to Separate Concerns

As Ryan said, this is the correct way to do it.

Controlling multiple states in a single useEffect() is extremely messy and sometimes impossible depending on what you want to achieve.

Nothing in the dependency array means the code will run when the ponent is mounted and is the functional equivalent to ponentDidMount().

When a value is in the array, the side effects trigger each time the value is updated.

As you can probably tell, using the same useEffect() for both of these things would be impossible.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742280947a4414465.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信