Search code examples
javascriptreactjsreduximmutabilityredux-thunk

Positioning logic for a network request in a React/Redux app


I have a React component that renders items on a page. The items are retrieved from the network.

These items should be retrieved and rendered when the component is loaded.

There will be a mechanism to update the items after the component has loaded too.

My first thought is to position the network request inside the componentDidMount function.

Would doing this break any of the best practises associated with redux and unidirectional data flow/immutability?

Instead, should I send an action to the store and rely on redux middleware to perform the network request (which will then eventually change the store and cause a re-render of the component)?


Solution

  • If your data is local, do it inside the componentWillMount,if your data is global then do it by calling an action.

    So basically making async call in componentDidMount and componentWillMount is same. Most probably, async call in componentWillMount wont return before componentDidMount is fired. But it will return before than if you make the same call in componentDidMount.

    Making async call in componentDidMount makes it clear that component will first render without data and then re-render when data arrives which is implicit in componentWillMount.