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

124
Views
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 answers
Answer question

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 Report
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!