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

Boilerplate and scaffolding: Boards CLI

An Introduction to Prisma

ES6 Journey Through Design Patterns

Promises 🤝 and Async/Await 🤯

How to Typescripting (Part 2)

what is variable in programming

Top VSCode Extensions for React, React Native, JavaScript, and Productivity

cover image

Unit Testing React-Redux Hooks

Understanding RxJS by Implementing an Observable

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

Document Transition API — Creating a React Hook

React’s favorite warning: Each child in a list should have a unique ‘key’ prop

React component with p tags returned from mapped array, with key={index}

React.js tips for better performance. Part 1

How to create custom hooks in react ?