Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ES lint expecting to pass all the dependencies to useEffect hook

I have a react component using a useState hook. This hook is called inside a useEffect hook

const [items, setItems] = useState({});

useEffect(() => {
  const newItem = {
    [item._id]: options
  };
  setItems({...items, ...newItem});
}, [options]);

this works as expected, when options changes, I create a new item with those options.

However, when I run lint I get an alert saying the useEffect is missing some dependency, but I can’t pass item as a dependency as this will result in an infinite loop.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Am I missing something or there’s a better way to do this and I should always pass all the properties used inside the useEffect hook as dependencies?

>Solution :

If you do not want to have to pass items into the dependency array, and create an infinite loop, you can pass a callback function to setItems in order to access the items state.

const [items, setItems] = useState({});

useEffect(() => {
  setItems((currentItems) => { // Access the current `items` state
    const newItem = {
      [currentItem._id]: options
    };
    return { ...currentItems, ...newItem };
  });
}, [options]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading