Home > Back-end >  ES lint expecting to pass all the dependencies to useEffect hook
ES lint expecting to pass all the dependencies to useEffect hook

Time:01-13

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.

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?

CodePudding user response:

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]);

CodePudding user response:

This is actually not sync. So you have to do it as this

setItems(prevState => {...prevState, ...newItem});
  • Related