title: How to conveniently use a useState value in a stored function?
body: <p>I have a component that stores an array of items in a useState which are later displayed. This allows me to update the list and rerender it. I'm trying to create functions I can store and send to other components to allow them to sort my list and have the result displayed. Unfortunately, when I create and store a function, it only uses the initial value of the useState.</p>
  <p>For example, look at my code below:</p>
  <pre><code>export default function MyWindow ({someAccessor}) {
  
      const [objectList, setObjectList] = useState([])
  
      const sortObjects = () =&gt; {
          let newList = [...objectList]
          newList.sort(someSortFunction)
          setObjectList(newList)
      }
      
      const createAndSortObjects = () =&gt; {
          let newList = [1, 2, 3, etc.]
          newList.sort(someSortFunction)
          setObjectList(newList)
      }
      
      useEffect(() =&gt; {
          populateObjectListFunction() //Line 1
          someAccessor.passFunction(sortObjects) //Line 2
          someAccessor.passFunction(createAndSortObjects ) //Line 3
      }, [])
  
      return (
          &lt;div&gt;
              {objectList.mapTo(someComponentMap)}
          &lt;/div&gt;
      )
  
  }
  </code></pre>
  <p>In Line 3, if the createAndSortObjects funtion is called by the accessor, it is able to create a new array, sort it as needed, and then update my objectList variable. If I try to do the same with Line 2, however, it only uses the inital value of objectList, which is [], and replaces the array populated in Line 3.</p>
  <p>How can I conveniently fix this issue, and have Line 2 update the existing item? I think I could probably use a useRef and access the .current value in sortObjects, but this would mean I need two separate variables to keep track of one object. I also can't switch from my useState because then the components won't get rerendered when the list changes. What should I do?</p>