
If you’re like me and have been relying predominantly on class components in React, you’re probably familiar with methods such as componentDidMount, componentDidUpdate, and componentWillUnmount. When it comes to using hooks, though, useEffect can take the place of all three of the aforementioned lifecycle methods.
useEffect is passed a function that is called after each render. Let’s say I’m creating a teleportation device to change locations each week (1-52 for each week of the year) so that I always wake up somewhere new. (Anyone else miss traveling right now?) In the example below, I’m defining an async function and invoking it at the end of useEffect.

Notice the second argument given to useEffect. On line 14, I’m passing week into an array. This array (which in my case exists of only one object) is a variable that must change in order to invoke useEffect. My location will now only change at the beginning of each week.
Also note that I am using axios instead of fetch to pull data. If you want to know more about axios, this is a great reference explaining the difference between that and the native fetch API. This cheat sheet will help you get started writing axios requests.
A really nice thing about the useEffect hook is that you can have multiple of them. If you wanted to invoke a different piece of functionality based on a different condition, you could write a new useEffect function. You can also execute clean-ups at the end of useEffect to avoid leaks in memory. You can read more about clean-up functions and timing effects in the ReactJS documentation.
Thanks for reading!
Sources and Further Reading:
1. https://reactjs.org/docs/hooks-reference.html#useeffect
2. https://medium.com/@zach.gollwitzer/imperative-vs-declarative-programming-procedural-functional-and-oop-b03a53ba745c (a Medium post that talks about imperative programming as opposed to declarative; useful to help wrap your head around how useEffect adds an imperative dimension to React)
3. https://www.npmjs.com/package/axios (for installing axios)
