DEV Community

ANKUSH CHOUDHARY JOHAL
ANKUSH CHOUDHARY JOHAL

Posted on • Originally published at johal.in

Why cross-platform GraphQL checklist Preact: A Step-by-Step Guide

Why Cross-Platform GraphQL Checklist for Preact: A Step-by-Step Guide

Preact has emerged as a lightweight alternative to React for building cross-platform applications, offering a 3KB virtual DOM and compatible API. When paired with GraphQL—a query language for APIs that delivers only the data you need—developers gain a powerful stack for efficient, cross-platform development. This guide walks through the essential checklist and step-by-step implementation for integrating GraphQL into cross-platform Preact projects.

Why Use GraphQL with Cross-Platform Preact?

GraphQL solves common pain points in cross-platform development: over-fetching, under-fetching, and managing multiple endpoints. For Preact apps running on web, mobile (via Capacitor or React Native), and desktop (via Electron), a single GraphQL endpoint standardizes data fetching across all platforms. Preact’s small footprint ensures GraphQL integration doesn’t bloat your bundle, even on low-powered devices.

Cross-Platform GraphQL Checklist for Preact

Before diving into implementation, verify these prerequisites are met:

  • Node.js v16+ and npm/yarn installed
  • Preact CLI or Vite with Preact template set up
  • GraphQL server endpoint (e.g., Apollo Server, Hasura, or AWS AppSync)
  • Cross-platform tooling configured (Capacitor for mobile, Electron for desktop, if targeting those platforms)
  • TypeScript (optional but recommended for type-safe GraphQL queries)

Step-by-Step Implementation Guide

Step 1: Set Up Preact Project

Initialize a new Preact project using Vite for faster builds:

npm create vite@latest preact-graphql-demo -- --template preact
cd preact-graphql-demo
npm install
Enter fullscreen mode Exit fullscreen mode

For cross-platform mobile support, add Capacitor:

npm install @capacitor/core @capacitor/cli
npx cap init preact-graphql-demo com.example.preactgraphql
npx cap add android
npx cap add ios
Enter fullscreen mode Exit fullscreen mode

Step 2: Install GraphQL Dependencies

Install Apollo Client (the most popular GraphQL client) and its Preact/React compatibility helpers:

npm install @apollo/client graphql @apollo/client/preact
Enter fullscreen mode Exit fullscreen mode

Note: @apollo/client/preact provides a compatibility layer since Preact mirrors React’s API, so Apollo Client works seamlessly with minimal configuration.

Step 3: Configure Apollo Client

Create an Apollo Client instance pointing to your GraphQL endpoint. In src/apollo.js:

import { ApolloClient, InMemoryCache } from '@apollo/client';
import { setPreactContext } from '@apollo/client/preact';

const client = new ApolloClient({
  uri: 'https://your-graphql-endpoint.com/graphql',
  cache: new InMemoryCache(),
});

setPreactContext(client);

export default client;
Enter fullscreen mode Exit fullscreen mode

For cross-platform projects, ensure the GraphQL endpoint is accessible from all target platforms (use HTTPS for mobile/desktop builds to avoid mixed content errors).

Step 4: Wrap App with Apollo Provider

In your entry file (src/index.js or src/main.jsx), wrap the Preact app with ApolloProvider to make the client available across all components:

import { render } from 'preact';
import { ApolloProvider } from '@apollo/client/preact';
import App from './App';
import client from './apollo';

render(


  ,
  document.getElementById('app')
);
Enter fullscreen mode Exit fullscreen mode

Step 5: Write and Execute GraphQL Queries

Define a GraphQL query to fetch data. For example, a query to fetch a list of users:

import { gql } from '@apollo/client';

export const GET_USERS = gql`
  query GetUsers {
    users {
      id
      name
      email
    }
  }
`;
Enter fullscreen mode Exit fullscreen mode

Use the useQuery hook in a Preact component to fetch and render data:

import { useQuery } from '@apollo/client/preact';
import { GET_USERS } from './queries';

function UserList() {
  const { loading, error, data } = useQuery(GET_USERS);

  if (loading) return Loading...;
  if (error) return Error: {error.message};

  return (

      {data.users.map((user) => (
        {user.name} ({user.email})
      ))}

  );
}

export default UserList;
Enter fullscreen mode Exit fullscreen mode

Step 6: Handle Mutations (Data Updates)

For creating, updating, or deleting data, use GraphQL mutations with the useMutation hook. Example mutation to add a new user:

export const ADD_USER = gql`
  mutation AddUser($name: String!, $email: String!) {
    addUser(name: $name, email: $email) {
      id
      name
      email
    }
  }
`;
Enter fullscreen mode Exit fullscreen mode

Implement the mutation in a component:

import { useMutation } from '@apollo/client/preact';
import { ADD_USER } from './mutations';
import { GET_USERS } from './queries';

function AddUserForm() {
  const [addUser, { data, loading, error }] = useMutation(ADD_USER, {
    refetchQueries: [{ query: GET_USERS }], // Refetch user list after mutation
  });

  const handleSubmit = (e) => {
    e.preventDefault();
    const form = e.target;
    addUser({
      variables: {
        name: form.name.value,
        email: form.email.value,
      },
    });
    form.reset();
  };

  return (




        {loading ? 'Adding...' : 'Add User'}

      {error && Error: {error.message}}
      {data && User added successfully!}

  );
}

export default AddUserForm;
Enter fullscreen mode Exit fullscreen mode

Step 7: Optimize for Cross-Platform

Apply these optimizations for cross-platform Preact GraphQL apps:

  • Use persistent caching with Apollo Client’s InMemoryCache to reduce network requests on mobile/desktop.
  • Implement error boundaries to handle GraphQL errors gracefully across all platforms.
  • Use code splitting for GraphQL queries to reduce initial bundle size.
  • Test GraphQL integration on all target platforms (web, mobile, desktop) to ensure endpoint accessibility.

Conclusion

Integrating GraphQL into cross-platform Preact projects streamlines data management, reduces bundle bloat, and standardizes data fetching across platforms. Following this checklist and step-by-step guide ensures a smooth setup, letting you focus on building great user experiences. Start with the prerequisites, configure Apollo Client, and iterate on queries and mutations to fit your app’s needs.

Top comments (0)