4

I'm reading the doc here https://github.com/reactjs/react-redux/blob/master/docs/api.md

I'd like to use Stateless component as much as possible, but I cannot figure out how I'd go about the initial data payload. With a Stateful React component, My container and component would look:

// Container
const mapDispatchToProps = (dispatch) {
    return {
        fetchData: () => dispatch(fetchDataAction());
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);

// Component
class MyComponent extends React.Component {
    componentDidMount() {
        this.props.fetchData();
    }
}

Where does the logic of componentDidMount go if I make my component stateless?

I've seen examples, where they suggest you extend your stateless component in your container with stateful React, and add that logic there:

// Container
class MyComponentContainer extends MyComponent {
    componentDidMount() {
        this.props.fetchData();
    }
}


export default connect(mapStateToProps, mapDispatchToProps)(MyComponentContainer);

But is that a best way to do it? If I am bothering to create a Stateful React, why not just do it directly on MyComponent?

EDIT Just to be clear; I'm asking if I can basically load my initial data WITHOUT ever creating a React.Component anywhere.

Kousha
  • 22,419
  • 30
  • 119
  • 232

2 Answers2

2

Related your main question: yes, it's totally possible to load data as soon as your store is created. Just use store.dispatch from any place in your code even outside React.Components.

You can check a simple example here. As you can see Components and data loading process are totaly separated from each other in it.

But is that a best way to do it? If I am bothering to create a Stateful React, why not just do it directly on MyComponent?

Indeed I don't see any reason to do anything like what you provided in the snippet. Even more, inheriting your Components from anything else than React.Component is definitely a smell in React world.

fkulikov
  • 2,839
  • 10
  • 23
0

you can dispatch an action in mapDispatchToProps but it is a dirty way and not at all recommended.

const mapDispatchToProps = (dispatch) {
    dispatch(fetchDataAction());
    return {
    }
}

But now mapDispatchToProps will not be pure as that's a side effect. Correct solution is to have a container component which will be stateful React Component and on Mount dispatch the action.

Another solution can be if you are using react-redux-router then:

Refer this: Should mapDispatchToProps dispatch initialization actions?

Eidt: similar question How to dispatch Redux action from stateless component when route is loaded?