2
votes

I'm doing a project using redux-hooks, I m new to redux-hooks. I am having actions.js file having different API call function. and to dispatch the action from a component using useDispatch(). do I have to import every function from actions.js to my different component to dispatch the action? or any methods are there? thanks in advance

1

1 Answers

2
votes

Before react-redux incorporated hooks into their library it was typical to split the parts of redux into their own container file. There you would map the actions and state that you needed into props that you would pass into the component. For example containers and components would look something like this.

Container Example.js:

// Node Modules
import {connect} from 'react-redux';

// Actions
import {action1, action2} from '../actions';

// Components
import ExampleComponent from './ExampleComponent';

// Actions
const mapDispatchToProps = (dispatch) => ({
  action1: () => dispatch(action1()),
  action2: () => dispatch(action2()),
});

// State
const mapStateToProps = (state) => ({
  state1: state.example.state1,
  state2: state.example.state2,
});

export const Example = connect(mapStateToProps, mapDispatchToProps)(ExampleComponent);

Component ExampleComponent.jsx:

// Node Modules
import React from 'react';

const Example = (props) => (
  <div>
    <label>{props.state1}</label>
    <label>{props.state1}</label>
    <button onClick={props.action1}>Action 1</button>
    <button onClick={props.action2}>Action 2</button>
  </div>
);

export default Example;

Although you could write both the container and component elements together in one file, this is just an example of how Redux could be used within React. With the introduction of hooks into react-redux you can now access the Redux store through their provided hooks.

Component ExampleComponent.jsx:

// Node Modules
import React from 'react';
import {useDispatch, useSelector} from 'react-redux';

// Actions
import {action1, action2} from '../actions';

const Example = (props) => {
  // Dispatch
  const dispatch = useDispatch();

  // Redux State
  const state1 = useSelector((state) => state.example.state1);
  const state2 = useSelector((state) => state.example.state2);
  return (
    <div>
      <label>{state1}</label>
      <label>{state1}</label>
      <button onClick={() => dispatch(action1())}>Action 1</button>
      <button onClick={() => dispatch(action2())}>Action 2</button>
    </div>
  );
};
export default Example;

With this method you can import your component directly from the ExampleComponent.jsx file instead of having to import it through a container. For your actions, you only need to import what you need to use for the component and wrap it with the dispatch hook that react-redux provides.