How to improve gatsby image querying for specific images

Viewed 238

just curious about any solutions which would help to reduce the pressure on the images query inside the Gatsby website. Gatsby already gives a warning that images query takes too long (we have around 600 images inside the website and it is growing quite fast).

Ideally I would like to fetch just a specific image each time, but do not really want to create static queries for each of them.

As of now, my query inside Image component is like this:

    query={graphql`
      {
        images: allFile(filter: { sourceInstanceName: { eq: "images" } }) {
          edges {
            node {
              relativePath
              name
              childImageSharp {
                gatsbyImageData(
                  quality: 100
                  layout: CONSTRAINED
                  placeholder: TRACED_SVG
                )
              }
            }
          }
        }
      }
    `}
    render={data => {
      const image = data.images.edges.find(n => {
        return n.node.relativePath.includes(filename);
      });
      if (!image) {
        return null;
      }

      const imageAlt = filename.split('.')[0];
      return (
        <GatsbyImage
          image={image.node.childImageSharp.gatsbyImageData}
          className={className}
          style={styles}
          alt={alt ? alt : imageAlt}
          fadeIn={false}
        />
      );
    }}
  />

I just want to hear any solutions anyone came up to work with for larger image databases on Gatsby :)

1 Answers

In the way you are using your Image component, you are forced to query and fetch 600 images each time you request an image because of the use of the StaticQuery or useStaticQuery hook (because they don't accept dynamic parameters). So basically, you get all the load to filter it and get only the desired picture.

I guess your only option here is to get rid of the static query and fetch that image in a page query based on some filter that should be lifted using the context or manually in the desired page (or based on some other page field). This way would be far way more optimal than requesting 600 images to render only 1.

Related