How I use React’s useEffect

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.

--

--

--

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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Hacks to improve React Native app performance

You probably shouldn't use XHR for building a Random Quote Generator

Learning by fixing: Node.js, modules and packages

Multiview support lands in Servo: architecture and optimizations

JSX — Syntactic Sugar for Writing React

Allow your mobile visitors to easier share your articles with the Web Share API

7 Browser-based Sandbox Tools for Testing Your Code

//platform.twitter.com/widgets.js from Twitter https://twitter.com/UKCareGuide

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Alex Loukissas

Alex Loukissas

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

More from Medium

Write or Not to Write. How and When Choose Libraries versus Own Code Implementations as a Team

A Flexible Way of Building

How to Write a Reusable React Loading Indicator

Config ESLint, Prettier in Typescript React App.