I was curious to know if making an API
request outside of the lifecycle/useEffect is a valid way to make the call?
https://stackblitz.com/edit/react-useeffect-button has two functional components, the parent component makes an API
call and passes the data to the child component
, initially specified the limit of data to be fetched from the endpoint as 2 and the parent component has a LoadMore
function that is passed as a prop
along with the data to the child component
.
Using the react-slick slider
to display the images in the child component
and the Load button onClick
will call the function LoadMore
inside the parent component and then it makes an API call and appends the new data from API to the old Data. The load button will append one Image to the existing images.
is this a good way to make API requests or should it be done only in the lifecycle methods?
is this a good way to make API requests outside useEffect/lifecycle.?
It depends on your requirements.
should it be done only in the lifecycle methods?
It depends on your requirements.
Then it will go into the infinite loop.
When do we make the request in useEffect and when by some other function?
Requests that fetch data or send some info at the time of initialization of the component is supposed to be made in componentDidMount/useEffect
And requests that are supposed to be sent on some action (like in your case, onClick) so they are hit according to that event.
There's neither good or bad, it's all about your requirements.
If you are making an API call to get data from initial render then using a lifecycle hook is a good approach. In your scenario, you want to make an API request when hitting a button. In that case it can be a simple function without any lifecycle hook method.
The only key part here is that you are maintaining the state and rendering the view from the state.
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