Search code examples
reactjstypescriptredux-toolkitrtk-query

RTK Query - query on mount when lazy is used


Is it okay to invoke rerender by making a request on mount? Or useEffect is neeeded? (Maybe lazy mode is different from ordinary query?)

export const Catalog: React.FC<CatalogProps> = ({ object, category }) => {
  const [getCatalogProducts, result] = useLazyGetCatalogProductsQuery();
  const { data, isUninitialized } = result;

  const request = `object_like=${object}&category=${category}`;

  if (isUninitialized) {
    getCatalogProducts(request);
  }

  if (!data) return;

  return (
    // some jsx code
  );
};

Solution

  • Is it okay to invoke rerender by making a request on mount?

    Yes, it's ok to do just about anything when the component mounts.

    Or useEffect is needed?

    Yes, you should use the useEffect hook to issue a side-effect when the component mounts.

    export const Catalog = ({ object, category }: CatalogProps) => {
      const [
        getCatalogProducts,
        { data, isUninitialized }
      ] = useLazyGetCatalogProductsQuery();
    
      useEffect(() => {
        const request = `object_like=${object}&category=${category}`;
    
        if (isUninitialized) {
          getCatalogProducts(request);
        }
      }, []); // <-- empty dependency array, run once after initial render cycle
    
      if (!data) return;
    
      return (
        // some jsx code
      );
    };
    

    Maybe lazy mode is different from ordinary query?

    Yes, it certainly is. The main difference is that the regular queries are automatically triggered and the lazy queries are not. Generally you'll use the regular queries since the "lazy" queries are more of an "on-demand" situation, e.g. user clicks a button and you want the query to run. The regular queries will also be initialized when the component mounts.

    You can review the Hooks Overview to get the complete rundown on differences.

    enter image description here