React useEffect Hook when only one of the effect's deps changes, but not the others

后端 未结 6 651
小蘑菇
小蘑菇 2020-12-13 14:01

I have a functional component using Hooks:

function Component(props) {
  const [ items, setItems ] = useState([]);

  // In a callback Hook to prevent unnece         


        
6条回答
  •  一生所求
    2020-12-13 14:41

    From the example provided, your effect does not depend on items and itemId, but one of the items from the collection.

    Yes, you need items and itemId to get that item, but it does not mean you have to specify them in the dependency array.

    To make sure it is executed only when the target item changes, you should pass that item to dependency array using the same lookup logic.

    useEffect(() => {
      if (items) {
        const item = items.find(item => item.id === props.itemId);
        console.log("Item changed to " item.name);
      }
    }, [ items.find(item => item.id === props.itemId) ])
    

提交回复
热议问题