How to pass an array to useEffect dependency list in React?

Sometimes, we want to pass an array to useEffect dependency list in React.

In this article, we’ll look at how to pass an array to useEffect dependency list in React.

How to pass an array to useEffect dependency list in React?

To pass an array to useEffect dependency list in React, we can pass in the array state into the dependencies list.

For instance, we write:

import React, { useEffect, useState } from "react";

export default function App() {
  const [nums, setNums] = useState([]);

  useEffect(() => {
    console.log(nums);
  }, [nums]);

  return (
    <>
      <button onClick={() => setNums((nums) => [...nums, nums.length + 1])}>
        insert number
      </button>
      <p>{JSON.stringify(nums)}</p>
    </>
  );
}

We have the nums array state we created with the useState hook.

Then we call useEffect with a callback that logs the current value of nums.

We watch the value of the nums array by passing it into the dependencies array.

Finally, we have a button that inserts a number into nums when we click it.

Now we should see the nums state logged when we click on the button.

Conclusion

To pass an array to useEffect dependency list in React, we can pass in the array state into the dependencies list.