1

It was an interview question (saw it somewhere online) and have researched but could not really find answers.

How can I prevent re fetching data when component re renders? I dont mean limiting it to being fetched only once (that I could do by making the request inside the constructor function).

Also, the only thing I found was a quick mentioning of using an external (to the react app) api. I do not understand what that means and how this can prevent data from being refetched.

Thanks a lot!

3
  • 1
    It's really hard to guess. Post some code reproducing exactly what your problem is Commented Nov 5, 2019 at 13:55
  • was that everything that was in your question? no more information? Commented Nov 5, 2019 at 13:58
  • I dont have code. It was an interview question. Commented Nov 5, 2019 at 14:01

1 Answer 1

3

Say you want to execute your function fetchData only when the component mounts (created and inserted into the DOM for the first time), but not when it re-renders. Then you can use:

In class components:

componentDidMount() {
  fetchData();
}

In function components with hooks:

useEffect(fetchData, []);

The second argument will watch for changes to the state passed into the array. Passing an empty array will simulate a componentDidMount

Sign up to request clarification or add additional context in comments.

5 Comments

Yes, but componentDidMount is called after each render, so the data would be refetched each time the component rerenders
that is not true.
@javascripting Where did you get that componentDidMount will be called after each render? It will be fired just once when the screen first mount. This is usually the place where all fetch calls are called.
@javascripting I guess you confuse it with componentDidUpdate
I guess there are many things that cause rerender, such as componentDidUpdate, parent component update (props update), or if you use hooks there are dependencies in square bracket

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.