I am using React-Redux to build an application.
To load initial data for a React smart ponent, I need to dispatch a Redux action where the server data requests will happen.
I've tried dispatching the action in constructor (ES6 implementation), ponentWillMount
, and ponenetDidMount
. They all worked.
My question is:
is there a remended place in the React smart ponent that the action should be dispatched.
I am using React-Redux to build an application.
To load initial data for a React smart ponent, I need to dispatch a Redux action where the server data requests will happen.
I've tried dispatching the action in constructor (ES6 implementation), ponentWillMount
, and ponenetDidMount
. They all worked.
My question is:
is there a remended place in the React smart ponent that the action should be dispatched.
Share Improve this question edited Jul 4, 2019 at 8:33 vsync 131k59 gold badges340 silver badges422 bronze badges asked Sep 21, 2016 at 15:19 JaneJane 6511 gold badge7 silver badges10 bronze badges2 Answers
Reset to default 8Edit: Dan Abramov recently stated
In future versions of React we expect that ponentWillMount will fire more than once in some cases, so you should use ponentDidMount for network requests.
In ponentDidMount
Read here.
Fetch data in ponentDidMount. When the response arrives, store the data in state, triggering a render to update your UI.
When fetching data asynchronously, use ponentWillUnmount to cancel any outstanding requests before the ponent is unmounted.
Documentation is really scarce on "why in ponentDidMount
". I believe ponentWillMount
is not called if you use server-side render, so this could be a reason why ponentDidMount
is preferred.
The remended way is, I believe, to do it in ponentDidMount. See this for more info.