Use react redux useSelector to select state based on current URL pathname

116 Views Asked by At

Assume I have the following redux rootReducer.

export const rootReducer = combineReducers({
  pages: pagesReducer,
})

And inside the pages state, i have the following data structure.


{
  '/info/read-more': { ...data },
  '/home': { ...data },
  '/profile/picture': { ...data },
  ...
}

Whenever I am in a component, i would like to select the pages state property based on the current pathname in the URL.

Here is what I am thinking of doing.

const location = useLocation()

const pageData = useSelector((state) => state.pages[location.pathname])

Is this going to be performant? Is it ok to use the location object inside the query function? Will it rerender all the time? Should i specify something in the compare function?

Any thoughts on this is much appreciated!


BACKGROUND: The app I am working on is heavily 'controlled' by a CMS. The app does not know what content to show before a response from the current URL is recieved. We have been using react-query for some time, but since the complexity has increased, I am considering moving all of the state managment over to redux.

0

There are 0 best solutions below