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

125
Visualizações
How do I correctly initialize a function which interacts with the redux state?

Let's say I have the following function which returns a filepath from the state, based on the filename (as input parameter) and if it doesn't exist returns an URL from a server.

const getFilepath = (state: IRootState) => (url: string) => {
    const file = getFilenameByURL(state, url);
    return file ? file : getRemoteFilePath(url);
}

Now I have a component FileBrowser, which has a list of file names. Here, I want to initialize this function. Currently I'd do it like this:

const { getFilepathByFilename } = useSelector((state: IRootState) => ({ getFilepathByFilename: getFilepath(state)}))

Now when I want to access the path from an element in the list, I do it like this:

const filePath = getFilepathByFilename(fileName)

Now this seems to work, but I run into an infinite rerender loop because the getFilepath function in the FileBrowser gets set over and over again.

I feel like I'm implementing a wrong pattern here. How would I go about creating a function which accesses the state, but doesn't cause infinite rerenders? Thanks for your help!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

To persist function reference across rerender of component you can use useCallback, like this:

const getFilepath = useCallback ((state: IRootState) => (url: string) => {
    const file = getFilenameByURL(state, url);
    return file ? file : getRemoteFilePath(url);
}, [])
about 4 years ago · Juan Pablo Isaza Relatório
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