React Hook has a missing dependency: ‘XXX’. Either include it or remove the dependency array

It is a common ESLint error in React. ESLint is a popular tool that helps developers catch and fix common programming mistakes.

When this error occurs, your code editor might display the following error message 👇

React Hook has a missing dependency: ‘XXX’. Either include it or remove the dependency array error pic 1

Why this error occurs ?

The error “React Hook has a missing dependency: ‘XXX’. Either include it or remove the dependency array” occurs when you use a “useEffect” or “useCallback” hook in your code, and you don’t include a dependency (like a variable or value) inside the dependency array.

However, you forget to add the value inside the dependency array. The dependency array is important because it tells the hook which values or variables it should pay attention to. If any of those dependencies change, the hook will run again.

Let’s say we want to display the message “hello world!” whenever our component is rendered, we can use the useEffect() hook with a console log inside it.

import { useEffect } from "react";

// ⛔️React Hook useEffect has a missing dependency:'setCenterPosition'.Either include it or remove the dependency array.(react-hooks/exhaustive-deps)
function App() {
  useEffect(() => {
    console.log("hello world!");
  }, []);
}

However, you might get an error stating “React Hook useEffect has a missing dependency: ‘setCenterPosition’. Either include it or remove the dependency array” This means that you need to include dependency(like a variable or value) in the dependency array or remove the dependency array altogether.

How to fix the error ?

To resolve the warning, you have two options:

1. Include the missing dependency in the dependency array:

import { useEffect } from "react";

function App() {
  useEffect(() => {
    console.log("hello world!");
  }, [dependency]);
}

If you want your useEffect() hook to run again every time a specific value changes, you can include that value as a dependency in the dependency array. This will ensure that the hook re-renders when the value you specify changes.

2. Remove the dependency array:

import { useEffect } from "react";

function App() {
  useEffect(() => {
    console.log("hello world!");
  });
}

If you don’t want your function to be called again when a specific value changes, you can remove the dependency array. In our case, since we want the function to run only once, we didn’t include a dependency array in the useEffect().

Note: Be careful when using this approach because it can cause unnecessary re-renders or outdated data if not used correctly.

I hope this article helped you to solve the error you were facing 🙏.

Leave a Comment