New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

react-query-hook-builder

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-query-hook-builder

A simple extension to help you create hooks that can be used inside your codebase

latest
Source
npmnpm
Version
0.0.7
Version published
Maintainers
1
Created
Source

React Query Hook Builder

A powerful tool to streamline your React Query development workflow. It automates the generation of type-safe hooks, API functions, query keys, and TypeScript types directly from OpenAPI specifications or manual inputs.

Available as both a VS Code Extension and an npm package for programmatic use.

Installation

VS Code Extension

Install from the VS Code Marketplace

npm Package

npm install react-query-hook-builder
# or
yarn add react-query-hook-builder

Features

🚀 OpenAPI / Swagger Support

  • Import from URL or JSON: Easily load your API specification by providing a URL or pasting the JSON content directly.
  • Batch Generation: Select multiple API endpoints at once to generate hooks in bulk.
  • Smart Detection:
    • Automatically maps GET requests to useQuery.
    • Maps POST, PUT, DELETE to useMutation.
    • Pagination Support: Detects paginated responses (e.g., fields like totalRecords) and generates useInfiniteQuery with mostly complete getNextPageParam logic.
  • Type Generation: Generates comprehensive TypeScript interfaces for:
    • Request Variables: Parameters (path/query) and request bodies.
    • Response Models: Strongly typed response objects, handling deeply nested structures and extracting cleaner names (e.g., UserData vs generic Response).

🛠️ Manual Hook Generation

  • Generate Hook from Specs: Don't have an OpenAPI spec? No problem.
    • Interactively provide the Feature Name, API URL, and HTTP Method.
    • Paste an example JSON response to automatically infer and generate TypeScript interfaces.

📦 Modular Code Generation

The extension generates four distinct parts for each hook, which can be placed in separate files or combined as needed:

  • Models/Types: TypeScript interfaces for the API response and variables.
  • API Function: An axios-based async function to make the network request.
  • Query Keys: A standardized factory object for React Query keys (supporting easy invalidation and scoping).
  • Hook: The custom React hook (useUser, useCreateUser, etc.) wrapping the React Query logic.

⚡ Developer Experience

  • Append to Files: Seamlessly append generated code to existing standard files (e.g., adding a new type to types.ts or a new hook to useHooks.ts).
  • History Support: Remembers your recently used OpenAPI URLs for quick access.
  • Formatting: Automatically formats generated code using a built-in Prettier implementation to match standard style guides.

Usage

VS Code Extension

  • Open the Command Palette (Cmd+Shift+P or Ctrl+Shift+P).
  • Run "React Query Hook Builder: Generate Hook from OpenAPI Spec".
  • Source: Select "Enter new OpenAPI Spec URL or JSON content" (or pick from history).
  • Select Endpoints: Choose one or more operations from the list.
  • Destination: For each component (Models, API, Keys, Hooks), choose to:
    • Select an existing file to append to.
    • Create a new file.
    • (The extension will remember your last used file for faster re-runs).

Method 2: Generate from Manual Specs

  • Open the Command Palette.
  • Run "React Query Hook Builder: Generate Hook from specs".
  • Follow the prompts:
    • Feature Name: e.g., TodoList.
    • Method: GET, POST, etc.
    • API URL: e.g., /api/todos.
    • Example Response: Paste a JSON sample from your backend to generate types.

npm Package (Programmatic Usage)

import { generateFiles, parseOpenApiSpec, formatCode } from 'react-query-hook-builder';

// Example 1: Generate from manual specs
const result = await generateFiles({
    featureName: 'getUserList',
    methodType: 'GET',
    apiUrl: '/api/users',
    exampleResponse: JSON.stringify({ users: [], total: 0 }),
    params: '',
    hookType: 'useQuery'
});

console.log(result.model);      // TypeScript interfaces
console.log(result.api);        // API function
console.log(result.queryKey);   // Query key factory
console.log(result.hook);       // React Query hook

// Example 2: Generate from OpenAPI spec
const openApiSpec = await parseOpenApiSpec('https://api.example.com/openapi.json');
// Process spec and generate hooks for specific operations

// Example 3: Format generated code
const formatted = await formatCode(result.hook, '/path/to/workspace');

API Reference

generateFiles(props: GenerateFilesProps): Promise<GenerateFileResponse>

Generates all parts (model, api, queryKey, hook) for a single endpoint.

Parameters:

  • featureName: string - Name of the feature (e.g., 'getUserList')
  • methodType: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
  • apiUrl: string - API endpoint URL
  • exampleResponse: string - JSON string of example response
  • params: string - JSON string of params/payload
  • hookType: 'useQuery' | 'useMutation' | 'useInfiniteQuery'
  • responseSchema?: string - Optional response schema
  • paramsSchema?: string - Optional params schema

Returns: Object with model, api, queryKey, and hook strings

parseOpenApiSpec(urlOrContent: string): Promise<OpenAPI.Document>

Parses an OpenAPI specification from URL or JSON string.

formatCode(code: string, workspacePath?: string): Promise<string>

Formats TypeScript code using Prettier.

Requirements

  • VS Code ^1.90.0
  • A project using react-query (TanStack Query) and axios. generated code assumes standard axios and react-query imports.

Extension Settings

This extension currently does not contribute any global settings. It relies on interaction during generation to determine file paths.

Known Issues

  • The extension assumes a standard response wrapper pattern (e.g. { data: T, success: boolean }) for some heuristic optimizations, but generally supports standard OpenAPI schemas.
  • Automatic import resolution is currently disabled; you may need to add imports (e.g., import { useQuery } from '@tanstack/react-query') to your files manually if they are not already present.

Enjoy faster React Query development!

Keywords

react-query

FAQs

Package last updated on 30 Dec 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts