How I use React’s useEffect

As if reasoning with component lifecycles in React class components wasn’t hard enough, things got even trickier with the advent of React functional components and the useEffect hook. Here’s how I ended up using them.

Photo by Ferenc Almasi on Unsplash
  1. Start with an empty dependency array. This means that your effect will only run once. Often times, this is what you want.
  2. Enable the exhaustive-deps rule from the eslint-plugin-react-hooks in your ESLint configuration. This will give you a warning you if your effect is using dependencies that you’re not capturing in your dependency array.
  3. Think of the dependency array as “when this effect will run”, not whether. This means, the effect will run whenever anything in the dependency array has changed.
  4. To have better control of “whether this effect will run”, consider using a ref. For example, if you only want to run this effect once, using a ref can make this deterministic (and easier to reason when reading the code). This could be useful, e.g. if your dependency array contains a context, which may be modified from another component unbeknownst to you.

Of course, it’s React’s philosophy that there isn’t one way of doing things, nor is there “one blessed way” in the documentation. So, this is why the title of this post is “How I use React’s useEffect”. Buyer beware :)

Co-founder & CTO @ AgentRisk. Former infra-tech guy (storage, networks). Startup nerd. Always building cool side-projects. #LongLA