Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to place logic for loading initial server data in React app?

I am using React-Redux to build an application.

To load initial data for a React smart component, I need to dispatch a Redux action where the server data requests will happen.

I've tried dispatching the action in constructor (ES6 implementation), componentWillMount, and componenetDidMount. They all worked.


My question is:

is there a recommended place in the React smart component that the action should be dispatched.

like image 971
Jane Avatar asked Sep 21 '16 15:09

Jane


People also ask

Where do you put logic in react?

model-view-controller. reactjs.

Which is the place where the application state and logic are held in react JS?

Store − Store is the place where the application state and logic are held. Every store is maintaining a particular state and it will update when needed. View − The view will receive data from the store and re-render the app.

Where is the best place to initialize react components?

The obvious constructor One obvious place to initialize is the constructor of the component. Similar to the following: class Contacts extends React.

How do you add a loading state in react?

Displaying the loading state in React is very simple. We can do it using the React useState hook, which allows us to track the state of a functional component. If you are interested to learn more about them, check out our previous guide about consuming an API in React using React Hooks.


2 Answers

Edit: Dan Abramov recently stated

In future versions of React we expect that componentWillMount will fire more than once in some cases, so you should use componentDidMount for network requests.


In componentDidMount

Read here.

Fetch data in componentDidMount. When the response arrives, store the data in state, triggering a render to update your UI.

When fetching data asynchronously, use componentWillUnmount to cancel any outstanding requests before the component is unmounted.

Documentation is really scarce on "why in componentDidMount". I believe componentWillMount is not called if you use server-side render, so this could be a reason why componentDidMount is preferred.

like image 176
Lyubomir Avatar answered Sep 19 '22 14:09

Lyubomir


The recommended way is, I believe, to do it in componentDidMount. See this for more info.

like image 28
Horia Coman Avatar answered Sep 20 '22 14:09

Horia Coman