skip to Main Content

I am building a project using typescript and react, with Redux Toolkit.
Now I find that I need to write sometime the same selectors again and again.
for example const userRole = useAppSelector((state)=> state.user.role),
I want a method to write it once and export it, is there a way to make this
more modular?
thank you!

2

Answers


  1. You literally write a selector function.

    export const selectRole = (state)=> state.user.role
    

    And then

    const userRole = useAppSelector(selectRole)
    
    Login or Signup to reply.
  2. You can create custom hook

    const useUserRole = () => useAppSelector((state) => state.user.role)
    

    And then use it like this, inside a component or inside another custom hook:

    const role = useUserRole()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search