Reputation: 107
I'm learning ReactJS
currently and I've seen and read that you should use componentDidMount
and componentDidUpdate
but I don't Understand why should I use it when the side effect is connected to the view.
For an example, I have a submit button in a sign in page, when should I send the api the sign in data? in componentDidMount
? or onSubmitHandler
?
Upvotes: 0
Views: 107
Reputation: 222
As mentioned in the other answers it completely depends upon the use cases, you can call your API in componentDidMount or in onSubmitHandler
.
Some common use cases:
ComponentDidMount
to simply call the API. I will not wait for any click event from user. If someone told you "you should use componentDidMount", then they are probably talking about this use case. Why call API in ComponentDidMount
There is an awesome article about the lifecycles React 16 Lifecycle Methods: How and when to use them
Upvotes: 0
Reputation: 1278
I'm not sure the context where some one told you "you should use componentDidMount
", but your submit button should call a function you define like "onSubmitHandler
".
componentDidMount
and componentDidUpdate
are called lifecycle methods and you should read about them before deciding if you should use them, and what you should use them for.
Upvotes: 1
Reputation: 2889
You should call your api in onSubmitHandler
and call it as per your use case.
As for the the componentDidMount
, it is generally used to call those methods which are required when a component is mounted.
You can read about lifecycle methods here
Upvotes: 1