React Apollo useQuery - how it works

Viewed 1293

Trying to understand how useQuery executes in background. When the Booklist component is rendered first , booklist function is called and usequery hook being called it returns loading set to true and starts executing the graphql request in the background. When it retrieves response from server it updates the properties and the component gets rerendered again , the function BookList is being called again from the begining. What happens when useQuery being called again does it place another request or takes the data from cache? How does it work.

Pasted the code below

import React, { Component } from 'react';
import { graphql } from 'react-apollo';
import {  useQuery } from "@apollo/react-hooks";
import gql from "graphql-tag";



function BookList() {
    console.log('Inside booklist')
    const { loading, error, data } = useQuery(gql`
      {
        countries {
            full_name_english
            full_name_locale
          }
      }
    `);
    console.log('Inside booklist1')
    if (loading) return <p>Loading...</p>;
    if (error) return <p>Error :(</p>;

        console.log('iam here22');
        console.log(data);
        // return (<div>completed</div>);
        return data.countries.map(({ full_name_english, full_name_locale },index) => (
            <div key={index}>
              <p>
                { full_name_english}: {full_name_locale}
              </p>
            </div>
          ));
  }
export default BookList;


App.js
function App() {
  return (
    <ApolloProvider client={client}>
      <div id="main">
            <h3> TEST APP</h3>
            <MyTest />

            <BookList/>

      </div>
    </ApolloProvider>

  );
}
export default App;
1 Answers

useQuery is a custom hook provided by apollo and it uses react hooks internally.

Now the way react hooks work is that when the first time they are rendered they use the values passed as arguments to them and store the result in memory

Now whenever the component renders is future, the arguments from the hooks are not used but the value from cache is returned. Any update to the value using the setter methods is being applied to the in memory results

Now useQuery also works on the same principle, the query passed to it is only used once and on future renders the value from cache is returned

You can check in the react docs about lazy initial state

Related