How to access react contexts and/or hooks in redux actions

Viewed 617

Could someone please tell me if it is a good idea to access contexts and/or hooks in redux actions or would it be better to always pass them as arguments from components.

Currently the only way I have managed to do this is by creating a custom dispatch hook:

function useDispatchWithHooks () {
    const dispatch = useDispatch();
    const hooks = {...useContext(AlertContext), ...useContext(WindowContext), ...useTranslation(), etc... };

    return (action) => {
        if (typeof action === 'function') {
            return action({ ...hooks }, dispatch);
        }

        return dispatch(action);
    }
}

Usage:

   const dispatch = useDispatchWithHooks();

    dispatch (({showAlert, translate}, dispatch) => {
        showAlert(translate('alert'), translate('createdTab'));
        dispatch( { type: INITIALIZE_TAB });
    });
0 Answers
Related