Search code examples
reactjsdesign-patternsreduxcomponentsdispatch

Using actions on React without a Dispatch function is correct?


I'm implementing Redux on React and it's currently working, but I'm not sure if it's correct. I have a redux folder with 3 files: actions, reducers and store.

Actions has this code:

export const SETTER_USER = "SETTER_USER"

export const setterUserAction = ({ email, username, role, lastVideo }) => ({
  type: SETTER_USER,
  payload: { email, username, role, lastVideo }
})

I'm calling this action from the component, this is the code on the component:

import React, { useState, useEffect } from "react";
import { connect } from 'react-redux'
import { setterUserAction } from '../../redux/actions'
...

const Login = ({ navigation, user, setUser }) => {
...
}

const mapStateToProps = state => ({
  user: state.user
})

const mapDispatchToProps = ({
  setUser: setterUserAction
})

export default connect(mapStateToProps, mapDispatchToProps)(Login)

I used to have the action inside the component, which I can imagine is not ideal. So I moved it to an actions.js file. But now I'm not using a dispatch function, which feels weird as dispatch is part of the whole pattern. So, what do you think? Is this correctly implemented? Or it's just working by luck?


Solution

  • You are defining mapDispatchToProps as an object. It was recommended by react-redux team: You can read more about it in here: https://react-redux.js.org/using-react-redux/connect-mapdispatch#defining-mapdispatchtoprops-as-an-object

    We recommend always using the “object shorthand” form of mapDispatchToProps, unless you have a specific reason to customize the dispatching behavior.

    Update: If you are using Function component with Hook, you should use the React-Redux hooks API: https://react-redux.js.org/api/hooks

    We recommend using the React-Redux hooks API as the default approach in your React components. The existing connect API still works and will continue to be supported, but the hooks API is simpler and works better with TypeScript.

    But if you are using Class Component. You should use connect with mapDispatchToProps as an object instead of as a function.