Home > Net >  How do I correctly initialize a function which interacts with the redux state?
How do I correctly initialize a function which interacts with the redux state?

Time:02-15

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!

CodePudding user response:

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);
}, [])
  • Related