React setState function in useEffect
Short answer:

You can include setExpanded in the dependency array.

Long answer:

The function passed to useEffect will fire only when at least one of the dependencies changes:

useEffect(() =&gt; {
  // runs
  // - on mount
  // - on every render
})

useEffect(() =&gt; {
  // runs
  // - on mount only
}, [])

useEffect(() =&gt; {
  // runs
  // - on mount
  // - on renders where varA and/or varB change
}, [varA, varB])


You should avoid passing objects as dependencies, because they may trigger unnecessary re-renders. If varA is an object created on every render, it may have the same value but it won't be the same object, so it will be treated as change and fire up the useEffect. See the example below:

const varA = { a : 1 }
const varB = { a : 1 }

varA === varB // false


However, sometimes, certain objects are guaranteed to not produce this behaviour, and this is the case of the setState() function.
According to the React Hooks API docs:


  Note: React guarantees that setState function identity is stable and won’t change on re-renders.


This means that you can include it in the useEffect dependencies with no problem.