react redux using useSelector multiple times in app

Viewed 5502

Hello I am using a selector multiple times in my Application. Can I write the code once and import then the selector? I thought to write a custom hook but I think this it is not necessary. Here is my Selector:

const county = useSelector((state)=>{
    const id = state.user.id
    const name = state.user.name
    return state.users.filter((user) => user.name === name)[0].county
})

It would nice if I have something like this:

import {countySelector} from 'selectors'
const county = useSelector(countySelector)
2 Answers

You can pass arrow function in useSelector

export const countySelector = state => {
    const id = state.user.id;
    const name = state.user.name;
    return state.users.find(user => user.name === name).county;
};

// Usage
import { countySelector } from 'selectors';
const county = useSelector(countySelector);

Or create custom hook

const useCounty = () => {
    return useSelector(state => {
        const id = state.user.id;
        const name = state.user.name;
        return state.users.find(user => user.name === name).county;
    });
};

export default useCounty;

// Usage
import useCounty from 'useCounty';
const county = useCounty();

Standard redux template comes with redux toolkit and that comes with reselect. Here are some examples of how to create composable memoized selectors.

Related