• Home
  • Blog
  • Projects
  • Bookshelf
  • About
← Back to all posts

Suspense Plus GraphQL

Published ....
Last modified ....

Share this post on BlueskySee discussion on Bluesky


Collocating GraphQL queries with components doesn't mean that you need to fetch data for every component in your app separately.

One of the greatest features of adopting GraphQL in my opinion has been the drive to colocate data requirements with the components that render that data, this collocation has cut down on the hard split of container and presentational components and has made it easier to develop features and applications in small units of code (aka components).

One of the fears about this collocation of data fetching with components that i have heard a few coworkers discuss has been the idea that having a lot of components do data fetching all by themselves could lead to a lot of loading spinners on the application during initial load. This fear derives from the idea that if every component needs to fetch its own data then we would have hundreds of components kicking of an Ajax request and we would have to wait for all the requests to resolve before showing the whole application as it is meant to be shown to the user.

I think there are two pretty simple ways to get over this fear, the first is easy to accomplish today, and the second is how I see the future of collocated data queries with components evolving to. Both of these examples are tightly coupled to React and GraphQL libraries like Apollo, but could probably be adopted by other view and data fetching libraries soon enough.

Current Day Resolved Data Fetching

The current day pattern to get over the need for showing a lot of spinners for each component that needs to fetch data is to export the data requirement from each component as a GraphQL fragment that a parent can import and resolve in a large query.

This pattern would look something like this:

// Leaf Component
export default ({ data }) => ( ... )

export const queryFragment = gql`
  fragment CommentsPageComment on Comment {
    id
    postedBy {
      login
      html_url
    }
    createdAt
    content
  }
`

// Parent component
import Leaf, { queryFragment as leafFragment } from './leaf.js'

const appQuery = gql`
  query Comment($repoName: String!) {
    entry(repoFullName: $repoName) {
      comments {
        ...CommentsPageComment
      }
    }
  }
  ${leafFragment}
`;

export default function App({repoName}) {
  return (
    <Query query={appQuery} variables={{ repoName }}>
      {() => ( ... )}
    </Query>
  )
}

In this case each leaf component with some data dependencies exports the component as the default and then exports a named export of the query fragment that any parent can then either resolve in its own query, or forward on back up to a grandparent via another export.

This is still a manual process of exporting the query as a fragment from each component, but it makes the data contract of the component more explicit, and allows the consumer of the component to determine how it wants to handle data loading for the component.

Some of the flaws of this mechanism include:

  • Manual query composition in the parent
  • Needing to pass down the props correctly to the leaf node

Future State Resolved Data Fetching

Now that we have looked at what the current patterns are for handling collocated data requirements for components, lets take a peak at the potential future for data loading with components. In this section we are going to talk about some unstable API's that are part of the React library, and the related unstable React Cache library so some of this might change in the future.

So lets look at the above example and how it could be simplified using Suspense:

// Leaf component
import { createQueryResource } from 'future-graphql-library';

export const query = createQueryResource(() => gql`
  query Comment($repoName: String!) {
    entry(repoFullName: $repoName) {
      comments {
        id
        postedBy {
          login
          html_url
        }
        createdAt
        content
      }
    }
  }`,
  (props) => ({ repoName: props.repoName })
);

export const Fallback = () => ( ... );

export const duration = 500;

export default function Comments(props) {
  const data = query.read(props);
  return (
    ...
  );
}

// Parent component
import Comments, {
  query as commentsQuery,
  Fallback as CommentsFallback,
  duration as CommentsDuration
} from './leaf.js';

export default function App(props) {
  commentsQuery.preload(props);
  return (
    <>
      <Main/>
        <Suspense
          maxDuration={commentsDuration}
          fallback={<CommentsFallback />}
        >
          <Comments {...props} />
        <Suspense>
    </>
  )
}

In this example the comments component (leaf component) exports the following:

  • A query resources
  • A fallback component
  • A duration
  • and the component itself

These four things allow the parent consumer to preload the data requirement for the component, as well as use opinionated fallbacks and loading durations for the component. The parent component can decide to use local values for some parts of the Suspense API wrapped around the leaf component if it chooses to do so.

The future state ideal presented here might look like a bit more work than the current day state, however it allows both the parent and the leaf components to be more opinionated about their fallback states, as well as the loading requirements.

No longer does the parent component need to know where to compose the data fetching fragment exported from the leaf component, and it also doesn't need to worry about what values the leaf components query relies upon, it can forward all props down to the resource from the leaf.

This API enables a tighter coupling between a component and the data it requests, and also allows parent components to decide when and if they will preload the data requirements for a leaf component or if it doesn't need to preload those data requirements.

Ultimately the new Suspense and Concurrent React APIs in conjunction with GraphQL will offer more unique ways to allow developers to fetch data requirements while also taking the pain out of managing loading states for those data requirements.


Tags:

ReactGraphQLSuspenseWeb Development

Loading...

Related Posts

React

Multi-step Native HTML Forms

....

useInterval

....

Server Side Rendering Compatible CSS Theming

....

A quick tip to implementing CSS theming that's compatible with Server Side Rendered applications!

Resetting Controlled Components in Forms

....

A quick way to handle resetting internal state in components when a parent form is submitted!

Request for a (minimal) RSC Framework

....

Some features and functionality that I'd like within a React Server Component compatible framework.

Don't Break the Implicit Prop Contract

....

React components have a fundamental contract that is often unstated in their implementation, and you should know about it!

A Better useSSR Implementation

....

Replace that old useState and useEffect combo for a new and better option!

React Error Boundaries: Revisited

....

Revising my previous blog post on React Error Boundaries and my preferred go-to implementation!

Managing Complex UI Component State

....

A few thoughts on managing complex UI component state within React

Understanding React 16.3 Updates

....

A quick overview of the new lifecycle methods introduced in React 16.3

Web Development

Website Redesign v11

....

I've once again updated my personal website, this time powered by my own RSC framework and a custom CMS solution as well!

Onboarding Your New AI Teammate

....

Are we reinventing the wheel when it comes to onboarding new AI agents to a codebase, when we already have primitives available for onboarding humans?

Quick Tip - Theme Aware Images

....

Have you ever found the need to change the image you render on a web page based on the current preferred color scheme of your theme?

Async Class Creation In JavaScript

....

Have you ever wanted to create a class in JavaScript or TypeScript but also have the initialization be async? Here's a quick tip on a pattern that I've used in the past!

Website Redesign v10

....

I recently launched a rewrite and redesign of this personal website, I figured I'd talk a bit about the changes and new features that I added along the way!

Server Side Rendering Compatible CSS Theming

....

A quick tip to implementing CSS theming that's compatible with Server Side Rendered applications!

Podcasting By Hand

....

A brief overview on how we launched The Bikeshed Podcast, including a deep dive in our recording and distribution workflows!

Quick Tip - Specific Local Module Declarations

....

A quick tip outlining how to provide specific TypeScript type definitions for a local module!

On File-System Routing Conventions

....

Some rough thoughts on building a file-system routing based web application

You're Building Software Wrong

....

Slicing software: why vertical is better than horizontal.

Single File Web Apps

....

What if you could author an entire web application in a single file?

Resetting Controlled Components in Forms

....

A quick way to handle resetting internal state in components when a parent form is submitted!

A Quick Look at Import Maps

....

A brief look at Import Maps and package.json#imports to support isomorphic JavaScript applications!

Recommended Tech Talks

....

A collection of tech talks that I regularly re-watch and also recommend to everyone!

Request for a (minimal) RSC Framework

....

Some features and functionality that I'd like within a React Server Component compatible framework.

Bluesky Tips and Tools

....

A (running) collection of Bluesky tips, tools, packages, and other misc things!

The Bookkeeping Pattern

....

A quick look at a small but powerful pattern I've been leveraging as of late!

TSLite

....

A proposal for a minimal variant of TypeScript!

Monorepo Tips and Tricks

....

Sharing a few core recommendations when working within monorepos to make your life easier!

Next.js with Deno v2

....

This is a quick post noting that Next.js should now work with Deno v2!

Don't Break the Implicit Prop Contract

....

React components have a fundamental contract that is often unstated in their implementation, and you should know about it!

A Better useSSR Implementation

....

Replace that old useState and useEffect combo for a new and better option!

My Current Dev Setup

....

A quick look at the applications and tools that I (generally) use day to day for web development!

Abstract Your API

....

Proposing a solution for sharing core "business" logic across services!

Tip: Request and Response Headers

....

There's a common gotcha when creating Web Request and Response instances with Headers!

Using Feature Toggles to De-risk Refactors

....

Feature toggles are often underused by most software development teams, and yet offer so much value during not only feature development but also refactors

Hohoro

....

A quick introduction to my new side project, hohoro. An incremental JS/TS library build tool!

Custom Favicon Recipes

....

Two neat tricks for enhancing your site's favicon!

Corporate Sponsored OSS

....

The various risks and pitfalls of open source software run by corporations.

The Library-Docs Monorepo Template

....

A monorepo template for managing a library and documentation together.

Building Better Beacon

....

How we solved an almost show-stopping production bug, and how you can avoid it in your own projects.

Project Deep Dive: Tails

....

A(nother) deep dive into one of my recent side projects; tails - a plain and simple cocktail recipe app.

Churn Anxiety

....

When did semver major changes become so scary?

Service Monitors and Observability

....

Leveraging service monitors properly to improve service observability.

On Adopting CSS-in-JS

....

A brief recap of how Wayfair changed it's CSS approach not once but twice in the span of 5 years!

Project Deep Dive: Microfibre

....

A deep dive into one of my recent side projects; microfibre - a minimal text posting application

Pair Programming

....

Pair programming can be good sometimes - but not all the time

You've Launched, Now What?

....

A few thoughts on what to do after you launch a new project

Taking a Break

....

A few quick thoughts on burn out and taking a break

Managing Complex UI Component State

....

A few thoughts on managing complex UI component state within React

Understanding React 16.3 Updates

....

A quick overview of the new lifecycle methods introduced in React 16.3

CSS in JS

....

A few thoughts and patterns for using styled-jsx or other CSS-in-JS solutions

Redesign v6

....

A few thoughts on the redesign of my personal site, adopting Next.js and deploying via Now

JavaScript Weirdness

....

A few weird things about JavaScript

Calendar

....

Building a calendar web application