0

I have below code snippet:

const [state, setState] = useState(null);

{data, loading, error} = useQuery(SOME_QUERY, {fetchPolicy: 'no-cache'});

useEffect(() => {
  setState(data)
}, [data]);

This seems to only render twice, once for the first render, and second once the GQL call is completed. My doubt is why is this not leading to infinite re-renders?

Component render -> useQuery fires -> call completed -> state updated by useEffect -> another render happens -> useQuery again fires and so on.

Is useQuery internally managing all of this? I also see only one network call being made.

4
  • What do you mean by "useQuery fires"? The hook is called on every render, sure, but that doesn't mean it necessarily does anything, just like the useState and useEffect hooks you're using. Commented Mar 23 at 19:40
  • @Bergi what I mean by 'fire' is, will the useQuery not do a network call every-time it gets executed? if not, how does it determine when it should do it or not? even though I am specifying it should not use the cache using no-cache. Commented Mar 23 at 19:48
  • 1
    No, it does not do another network call every time the hook is called (every time the component is rendered), that would lead to an infinite loop even without your state and effect because the component renders when data/loading changes! It keeps a state internally (and probably uses an effect for making new requests when the query/variables change, and actually does some more fancy stuff). Commented Mar 23 at 19:52
  • understood, I guess then useQuery must be doing deep equality checks also if the query accepts a variable. Commented Mar 23 at 20:04

0

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.