Is a good practice to fetch data in javascript class constructor()
?
E.g. In react class constructor()
, every tutorial which I find fetch data in componendDidMount()
, but no one explein why We can't do it in constructor()
.
Question concerns javascript classes at all, not only react
.
Constructor is called before the component is mounted (as stated here in #constructor doc: https://reactjs.org/docs/react-component.html).
To answer your question, the explanation lies in the lifecycle of a react component and the need to redraw when the state changes. By doing async calls in constructor, you may trigger setState before your component is mounted.
Doing async calls in constructor will mess with the re-render and your component will sometimes not re-render if you call setState in the constructor.
From doc:
You should not call setState() in the constructor(). Instead, if your component needs to use local state, assign the initial state to this.state directly in the constructor:
Avoid introducing any side-effects or subscriptions in the constructor. For those use cases, use componentDidMount() instead.
A class constructor is a function which gets called only when function initialises for the first time in DOM. In trivial language behaviour, only when we instantiate a class using new keyword, its constructor gets called. Now if we fetch data in Javascript Classes constructor:
In case as React if the data fetched is responsible for interacting with DOM(UI), it will fail as DOM gets ready only after component mounts, assured by componentDidMount.
The Data fetching function will also not be called when component re renders as constructor is called only once and hence data wont update for UI(DOM)
Constructors are used generally for default value assignment and declaring class related attributes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With