You have a nagging feeling that you’re missing something. It seems similar to class lifecycles… but is it really? This deep dive into React world will make the answers to these questions look obvious to you. We recommend learning React’s useEffect with Dan Abramov.
- While you can
useEffect(fn, ), it’s not an exact equivalent. Unlike
componentDidMount, it will capture props and state. So even inside the callbacks, you’ll see the initial props and state. If you want to see “latest” something, you can write it to a ref. But there’s usually a simpler way to structure the code so that you don’t have to. Keep in mind that the mental model for effects is different from
componentDidMountand other lifecycles, and trying to find their exact equivalents may confuse you more than help.
- The recommendation is to host functions that don’t need props or state outside of your component and pull the ones that are used only by an effect inside of that effect. If after that your effect still ends up using functions in the rendered scope (including function from props), wrap them into
useCallbackwhere they’re defined, and repeat the process.
- An infinite loop may also happen if you specify a value that always changes in the dependency array. You can tell which one by removing them one by one. However, removing a dependency you use (or blindly specifying
) is usually the wrong fix. Instead, fix the problem at its source.
- Effects always “see” props and state from the render they were defined in. That helps prevent bugs but in some cases can be annoying. For those cases, you can explicitly maintain some value in a mutable ref (the linked article explains it at the end).
Enjoy the whole Dan Abramov’s article here.
In this article, we would tell you about React Spring animation package for React apps.