Do you make this mistake with useEffect in React?

Amit Kumar
Bits and Pieces
Published in
3 min readSep 7, 2022

--

Photo by Lewis Kang'ethe Ngugi on Unsplash

There is one hook used most commonly with the React function component. The hook is called the useEffect hook. This hook is used to tell React that your component needs to do something after rendering.

There is one mistake commonly made when using useEffect. It won’t look like much at the beginning but the issues it creates are very difficult to debug.

The mystery of useEffect dependencies

The useEffect hook accepts a list of dependencies. It tells React that whenever any of the dependencies changes, execute the callback function passed.

This is where the mistake is made. React provides a hook called useRef hook. The useRef hook is used when you want to keep track of a value. The special thing about this hook is that it doesn’t trigger a re-render when the value is updated.

With useRef hook the React guarantees that the object returned will be stored and associated with the current instance of the component as long as that component exists.

It is not a good practice to use useRef value inside the list of dependencies passed to useEffect. Since the useRef object instance never changes as long as the component exists, using that in the list of dependencies will not execute the useEffect callback.

Also using the ref.current in the list of dependencies is not a good idea because it will lead to surprising behaviour that's difficult to debug.

A close look at bug created with useEffect

Below app uses ref.current inside the list of dependencies for useEffect. Check out the surprising behaviour that leads to a bug. The code looks straightforward at the top, but under the hood, it’s creating a bug just because of ref.current in the list of dependencies. The useEffect hook is not executing and updating the state when used ref.current as a dependency.

A simple method to avoid this bug easily

Use this thumb rule and you won’t encounter this bug in the future: Never use those things in your useEffect dependency array that won’t trigger a re-render when updated. Dependencies should only include values that participate in top-down React data flow. Such as props, state, and what you calculate from them.

Read this post and more on my Typeshare Social Blog

Go composable: Build apps faster like Lego

Bit is an open-source tool for building apps in a modular and collaborative way. Go composable to ship faster, more consistently, and easily scale.

Learn more

Build apps, pages, user-experiences and UIs as standalone components. Use them to compose new apps and experiences faster. Bring any framework and tool into your workflow. Share, reuse, and collaborate to build together.

Help your team with:

Micro-Frontends

Design Systems

Code-Sharing and reuse

Monorepos

--

--

Amit Kumar is a frontend developer who love designing web applications with clean, consistent User Interface.