I use reselect library with my react-native project. I have the following code.
import { createSelector } from 'reselect';
import { ApplicationState } from 'types/reducer.types';
const selectAuth = ({ auth }: ApplicationState) => auth;
export const selectFirstName = createSelector([selectAuth], auth => auth.user?.firstName);
export const selectLastName = createSelector([selectAuth], auth => auth?.user?.lastName);
In the container the code is like this.
import { connect } from 'react-redux';
// import { useSelector } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import { signOut } from 'Redux/auth/auth.actions';
import { selectFirstName, selectLastName } from 'Redux/auth/auth.selectors';
import CustomDrawer from './custom-drawer.component';
const mapStateToProps = createStructuredSelector({
firstName: selectFirstName,
lastName: selectLastName,
});
export default connect(mapStateToProps, { signOut })(CustomDrawer);
Now I want to use useSelector hook. I tried several ways but it didn't work. How can this be done?
createStructuredSelector
returns a selector (a function that takes state
and returns an object {firstName, lastName}
), so you can use it inside of useSelector
const {firstName, lastName} = useSelector(createStructuredSelector({
firstName: selectFirstName,
lastName: selectLastName,
}));
or using your existing variable
const {firstName, lastName} = useSelector(mapStateToProps);
However there's not really any point in combining and then destructing the properties when you can use many useSelector
hooks in one component.
const firstName = useSelector(selectFirstName);
const lastName = useSelector(selectLastName);