Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

120
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda