facebookarchive / redux-react-hook

React Hook for accessing state and dispatch from a Redux store
MIT License
2.16k stars 103 forks source link

useMappedState should have selectors as dependencies #41

Closed otakustay closed 5 years ago

otakustay commented 5 years ago

When state is mapped to an object or array like:

const getUsers = useCallback(
    state => {
        const ids = state.userIds;
        return ids.map(id => state.userStore[id]);
    },
    []
);
const users = useMappedState(getUsers);

The returning users can be a new array instance each time this component renders, passing users to a sub component could cause a re-render even userIds and userStore are not modified.

I'd rather to provide a more reselect like API:

const getUsers = useCallback(
    (ids, userStore) => ids.map(id => userStore[id]),
    []
);
const users = useMappedState(
    getUsers,
    [state => state.userIds, state => state.userStore]
);

In which the values returned by the second argument become dependencies to a useMemo call.

ianobermiller commented 5 years ago

You can already use reselector (or any other) selectors with redux-react-hook. We shouldn't expand the scope of redux-react-hook to include selectors. Especially since not everyone uses the same selector library or the same configurations of reselect for that matter. This would be a perfect use case for a custom hook.