React useEffect Hook when only one of the effect's deps changes, but not the others : <p>I have a functional component using Hooks:</p>

<pre><code>function Component(props) {
  const [ items, setItems ] = useState([]);

  // In a callback Hook to prevent unnecessary re-renders 
  const handleFetchItems = useCallback(() =&gt; {
    fetchItemsFromApi().then(setItems);
  }, []);

  // Fetch items on mount
  useEffect(() =&gt; {
    handleFetchItems();
  }, []);

  // I want this effect to run only when 'props.itemId' changes,
  // not when 'items' changes
  useEffect(() =&gt; {
    if (items) {
      const item = items.find(item =&gt; item.id === props.itemId);
      console.log("Item changed to " item.name);
    }
  }, [ items, props.itemId ])

  // Clicking the button should NOT log anything to console
  return (
    &lt;Button onClick={handleFetchItems}&gt;Fetch items&lt;/Button&gt;
  );
}
</code></pre>

<p>The component fetches some <code>items</code> on mount and saves them to state.</p>

<p>The component receives an <code>itemId</code> prop (from React Router).</p>

<p>Whenever the <code>props.itemId</code> changes, I want this to trigger an effect, in this case logging it to console.</p>

<hr>

<p>The problem is that, since the effect is also dependent on <code>items</code>, the effect will also run whenever <code>items</code> changes, for instance when the <code>items</code> are re-fetched by pressing the button.</p>

<p>This can be fixed by storing the previous <code>props.itemId</code> in a separate state variable and comparing the two, but this seems like a hack and adds boilerplate. Using Component classes this is solved by comparing current and previous props in <code>componentDidUpdate</code>, but this is not possible using functional components, which is a requirement for using Hooks.</p>

<hr>

<p><strong>What is the best way to trigger an effect dependent on multiple parameters, only when one of the parameters change?</strong></p>

<hr>

<p><em>PS. Hooks are kind of a new thing, and I think we all are trying our best to figure out how to properly work with them, so if my way of thinking about this seems wrong or awkward to you, please point it out.</em></p>
