Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

108
Views
How to conveniently use a useState value in a stored function?

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.

For example, look at my code below:

export default function MyWindow ({someAccessor}) {

    const [objectList, setObjectList] = useState([])

    const sortObjects = () => {
        let newList = [...objectList]
        newList.sort(someSortFunction)
        setObjectList(newList)
    }
    
    const createAndSortObjects = () => {
        let newList = [1, 2, 3, etc.]
        newList.sort(someSortFunction)
        setObjectList(newList)
    }
    
    useEffect(() => {
        populateObjectListFunction() //Line 1
        someAccessor.passFunction(sortObjects) //Line 2
        someAccessor.passFunction(createAndSortObjects ) //Line 3
    }, [])

    return (
        <div>
            {objectList.mapTo(someComponentMap)}
        </div>
    )

}

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.

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!