Or Orsatti
Or Orsatti

Reputation: 107

What is the best practice cause side effects, such as connecting to a webapi, in reactjs, and why?

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

Answers (3)

Rahul Saini
Rahul Saini

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:

  • When I want to call an API after my view rendered then I will use 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

  • If there is a submit button on my page and I want to call API when someone clicks on that then I will use onClick event. I can't call API in ComponentDidMount in that case

There is an awesome article about the lifecycles React 16 Lifecycle Methods: How and when to use them

Upvotes: 0

SpeedOfRound
SpeedOfRound

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

Utsav Patel
Utsav Patel

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

Related Questions