How to avoid API requests getting called repeatedly in your React component

If you have a React class component OR functional component, and are using fetch, axios, etc. to make a call to the server, you may want to only do that once when the component is created. This is easy to set up for both class components and function components.

If you stumbled across this problem it is because you are either trying to build a React component without a solid understanding, or you are doing a course that is teaching you thinks in the wrong order. The remedy for both of these things is to read through the official React documentation.

If you are working on a function component – read about the useEffect hooks – read both of those sections in detail and make sure you really understand it.

For class components, read about componentDidMount.

The trick is – don’t make API calls from the render() method of your class component or the function of your function component, unless you want that API call to happen on every render, which I very much doubt, and I cannot think of a use for.

I have pointed you at specific documentation, but the more you read and understand about React before you start, the fewer problems you will encounter like this.

Notice I didn’t answer the question! That was on purpose, because the temptation is to think “ah it’s fixed I’m done”, when investing some time in understanding React better will pay off for itself very quickly, and then many times over.

Feel free to contact me if you have any questions, or you can ask on Reddit.

Posted by Martin Capodici

.

Leave a Comment

Your email address will not be published. Required fields are marked *