A Visual Guide to React's useEffect (2021)
Lots of people seem to misunderstand useEffect. It's not for transforming local state or for handling user events. In fact, there are many many reasons that people use useEffect for where it's not needed, and the recent React beta docs address this [0]. Their categories include:<p>- Updating state based on props or state<p>- Caching expensive calculations<p>- Resetting all state when a prop changes<p>- Adjusting some state when a prop changes<p>- Sharing logic between event handlers<p>- Sending a POST request<p>- Chains of computations<p>- Initializing the application<p>- Notifying parent components about state changes<p>- Passing data to the parent<p>- Subscribing to an external store<p>- Fetching data<p>Effects should also be idempotent, they should include pure functions that don't have side effects (such as doing a POST request) which Dan Abramov of the core React team addresses [1].<p>[0] <a href="https://beta.reactjs.org/learn/you-might-not-need-an-effect" rel="nofollow">https://beta.reactjs.org/learn/you-might-not-need-an-effect</a><p>[1] <a href="https://twitter.com/dan_abramov/status/1281669881667162112" rel="nofollow">https://twitter.com/dan_abramov/status/1281669881667162112</a>