Search code examples
reactjsreduxreact-reduxredux-thunk

Why not dispatch directly into store from action creator redux?


I am building an app using redux and react-native.

I am curious about a pattern which I use. I have encountered no downsides however I haven't seen it in any tutorials which makes me wonder why nobody does it.

Instead of passing action creators as props in the connect function like

 connect(mapStateToProps,{ func1, func2 })(Component);

I imported the app store inside of the module where I declare the functions in the first place:

import { AppStore } from '../App';
const actionCreator = () => {
   doSomethng();
   appStore.dispatch({ type: 'Action' });
};

This to me makes it easier to do async actions because I need no middleware:

import { AppStore } from '../App';
const actionCreator = async () => {
   await doSomethng();
   appStore.dispatch({ type: 'Action' });
};

I did this because of the js-lint error 'no-shadow'. It made me realise that in order to use it I had to import the action creators in the component file, and then pass it as a prop to the connect function in order for the action creator to have access to dispatch.

import { actionCreator1, actionCreator2 } from './actionCreators';

const myComponent = (props) => {
   const { actionCreator1, actionCreator2 } = props; //shadowed names
   return (
      <Button onPress={actionCreator1} />
   );
};

export default connect({}, { actionCreator1, actionCreator2 })(myComponent)

In my version I just import it once but do not pass it to connect. This eliminates the need to shadow names.

import { actionCreator1, actionCreator2 } from './actionCreators';

const myComponent = (props) => {
   return (
      <Button onPress={actionCreator1} />
   );
};

export default connect({})(myComponent)

Solution

  • I like that you try to find your own solutions to your specific problems. It's the sign of an engineer, just in this case this isn't the solution.

    I think the idea of how Redux teaches you to do things is not intended to be canonized. You have the ability to put a dispatcher on your props because it allows things to be transparent, meaning that things are bound outside of your class and injected in. You have hidden your store dependency by directly referencing it in some other files. It's no longer as obvious how your application works with regards to the workflow. Another react developer would be confused, I suppose that's the major downside.

    If you're ok with those aspects what you're doing is fine. Fine as in, it gets the job done, but not "fine" in that it embraces concepts like Single Responsibility Principle