Home > front end >  Is it possible to create a reusable function for useSelector?
Is it possible to create a reusable function for useSelector?

Time:12-10

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);

CodePudding user response:

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();
  // ...
}
  • Related