Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to create a reusable function for useSelector?

I am curious if there is a way to reuse useSelector in redux since I use it multiple times in different screens.

I tried creating a selector.ts file like this but it did not work since it is not inside the store and not a function component. Any idea how can I reuse this code?

export const branch = useSelector((state: any) => state.branchReducer.branch);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could stick the selector function into a file, then have each component import the selector and pass it into useSelector:

// selectors.ts
export const branchSelector = (state: any) => state.branchReducer.branch;

// used like:
import { branchSelector } from './some/path'
const Example = (props) => {
  const branch = useSelector(branchSelector);
  // ...
}

Or you could create custom hooks and use those:

// selectorHooks.ts
export const useBranch = () => useSelector((state: any) => state.branchReducer.branch);

// used like:
import { useBranch } from './some/path';
const Example = (props) => {
  const branch = useBranch();
  // ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading