React Query vs SWR: Which Data Fetching Library Should You Use?
React Query and SWR both eliminate hand-rolled fetch-plus-useEffect code, but they make different tradeoffs. React Query gives you fine-grained cache control, mutations, and background sync at the cost of more configuration; SWR is smaller and gets out of your way faster for read-heavy use cases.
React data fetching tools manage the full lifecycle of async server data inside components: issuing HTTP requests, caching responses, tracking loading and error states, and revalidating stale data. TanStack/query wraps any async function in a normalized cache with automatic background refetching. vercel/swr applies a stale-while-revalidate strategy via a single useSWR hook. axios/axios sits a level lower — it handles HTTP transport without touching React state at all.
TanStack/query is the default choice for most React teams. Install it with `npm install @tanstack/react-query`, add a QueryClientProvider at the root, then call useQuery({ queryKey: ['users'], queryFn: fetchUsers }) in any component. It handles caching, background refetching, pagination, and cache invalidation after mutations — all without a custom store or reducer. It works against any backend: REST, GraphQL, or serverless functions.
vercel/swr is the right pick for Next.js projects or teams wanting a minimal API: useSWR('/api/users', fetcher) returns data, error, and isLoading with no provider setup. For GraphQL-first apps, apollographql/apollo-client adds a normalized entity cache that merges partial query results — a feature TanStack/query intentionally omits. Teams building full-stack TypeScript monorepos should evaluate trpc/trpc, which eliminates the API contract entirely and ships its own TanStack/query integration.
If you're fetching from a REST or custom API in any React app, pick TanStack/query — it covers 80% of teams with no meaningful trade-offs. If your app is exclusively GraphQL, pick apollographql/apollo-client for its entity-level cache normalization. If you control both the Next.js frontend and the TypeScript backend in one repo, pick trpc/trpc. If you want the absolute minimum API surface for a Next.js or Vercel project, pick vercel/swr.
TanStack/query is the default choice for React data fetching. Install with `npm install @tanstack/react-query`, add a QueryClientProvider, and call useQuery in any component. It handles caching, background refetching, mutations, and pagination for any backend — REST, GraphQL, or serverless — with no custom store.
vercel/swr is the leanest option for Next.js and Vercel projects. Its useSWR(key, fetcher) hook requires no provider setup, and its Next.js App Router integration is seamless. It trades TanStack/query's advanced mutation workflows and devtools for a dramatically smaller API surface.
TanStack
query
- 49,954Stars
- 21Hotness
- 89Reliability
- almost 7 yearsAge
TanStack/query is an async state management library for React that treats server data as a separate concern from client UI state. Install with npm install @tanstack/react-query, wrap your app in <QueryClientProvider client={new QueryClient()}> once, then call const { data, isLoading, error } = useQuery({ queryKey: ['posts'], queryFn: fetchPosts }) in any component. The library maintains an in-memory cache keyed by your query key arrays and tracks the full request lifecycle automatically — deduplicated concurrent requests, background revalidation on window focus, and configurable stale time per query.
Three core strengths: automatic background refetching keeps data fresh without manual polling; useMutation paired with queryClient.invalidateQueries gives surgical cache invalidation after writes; useInfiniteQuery handles paginated and infinite-scroll data with built-in page cursor management and a flat merged array. The React Query Devtools panel visualizes every cache entry and its staleness in real time. Drawbacks: query key discipline is required — keys that are too broad cause cache collisions, too narrow cause over-fetching; the v4-to-v5 migration introduced breaking changes; teams new to the server-state mental model find the paradigm shift takes time.
TanStack/query is the correct default for any React project fetching data from a REST, GraphQL, or serverless API. Reach for a competitor only in specific cases: apollographql/apollo-client if you need entity-level normalized caching for GraphQL, or trpc/trpc if your stack is TypeScript end-to-end and you ...
vercel
swr
- 32,434Stars
- 11Hotness
- 62Reliability
- over 6 yearsAge
vercel/swr is a React data fetching hook library built on the stale-while-revalidate caching strategy. Install with npm install swr, then call const { data, error, isLoading } = useSWR('/api/user', fetcher) — no provider or client setup required. The fetcher argument is any function returning a Promise; teams typically pass fetch or axios. SWR deduplicates requests sharing the same key within the same tick, revalidates automatically on window focus and network reconnect, and exposes a mutate function for manual cache updates and optimistic UI.
Strengths: the API surface is genuinely tiny — most teams need only useSWR, mutate, and <SWRConfig> for global defaults; Next.js App Router and server component integration is first-class given Vercel's ownership; prefetching with fallback data makes SSR hand-off trivial. Drawbacks: mutation handling is less ergonomic than TanStack/query — you call mutate(key, optimisticData) manually rather than using a structured useMutation hook with lifecycle callbacks; useInfiniteQuery-equivalent functionality exists but is less capable; the plugin and middleware ecosystem is smaller than TanStack/query's.
Pick vercel/swr if your project is a Next.js or Vercel-hosted app, you want the smallest possible API surface for data fetching, or you don't need complex mutation workflows. For applications with heavy write operations, optimistic updates, or pagination at scale, TanStack/query handles those scenarios more cleanly out of the box.
alovajs
alova
- 4,008Stars
- 1Hotness
- 46Reliability
- over 3 yearsAge
alovajs/alova is a request toolkit that combines HTTP requesting, caching, and React state management into a single library. Install with npm install alova, create an instance with createAlova({ requestAdapter: xhrRequestAdapter() }), and call const { data, loading, error } = useRequest(alovaInstance.Get('/api/users')) in a React component. Alova positions itself as a replacement for the combination of a transport library like axios plus a caching layer like TanStack/query, handling both layers in one package with built-in caching strategies (memory, session storage, persistent), request deduplication, and an offline-tolerant mutation queue it calls the silent queue.
Strengths: the unified API means one library instead of two for transport and React state; caching strategies are configurable per request with no additional setup; the silent queue allows mutations made offline to be replayed automatically on reconnect — a capability TanStack/query requires custom code to replicate. Drawbacks: the community and ecosystem are significantly smaller than TanStack/query's, meaning fewer Stack Overflow answers, fewer third-party integrations, and less production battle-testing at scale; documentation is primarily authored in Chinese with English translations that lag behind; TanStack/query has years of production use and a rich ecosystem of devtools, plugins, and framework adapters that alovajs/alova has not yet matched.
alovajs/alova is worth evaluating for teams that want a single unified request-plus-state library and are comfortable being early adopters of less-prove...
sindresorhus
ky
- 16,997Stars
- 40Hotness
- 1Reliability
- almost 8 yearsAge
sindresorhus/ky is a tiny, elegant HTTP client built directly on the Fetch API. Install with npm install ky, then call const data = await ky.get('/api/users').json(). Like elbywan/wretch it provides a fluent interface over fetch, but its emphasis is on correctness, type safety, and a clean hooks-based middleware API. It supports retry with exponential backoff via retry: { limit: 3 }, configurable timeouts, automatic Content-Type detection, and throws a typed HTTPError on non-2xx responses by default.
Strengths: the hooks API is cleaner than axios interceptors for many use cases — beforeRequest receives a typed Request object you can modify and return, afterResponse receives the typed Response; exponential backoff retry is built in with no extra setup; it is maintained by Sindre Sorhus with consistently high code quality and documentation. Drawbacks: it adds a dependency over native fetch that simple projects won't need; like all transport-only libraries it provides no React state management, caching, or loading states, so TanStack/query is still required; it has fewer advanced enterprise features than axios for scenarios like request cancellation queues or complex retry logic.
sindresorhus/ky is the best choice for teams that want a polished, modern fetch wrapper with hooks-based middleware and built-in retry, especially in TypeScript projects where the typed Request/Response objects are useful. Pair it with TanStack/query as the queryFn. For teams with existing axios interceptor setups, the incumbent advantage makes switching unlikely to pay off.
nestjs
nest
- 76,155Stars
- 27Hotness
- 87Reliability
- over 9 yearsAge
nestjs/nest is a TypeScript server-side framework for building scalable Node.js APIs using Angular-inspired architecture. Install with npm install @nestjs/core @nestjs/common, then define controllers with @Controller('users') and services with @Injectable(). NestJS uses a dependency injection container and TypeScript decorators to organize applications into modules, controllers, and providers. It runs on top of Express or Fastify and supports REST, GraphQL via @nestjs/graphql, WebSockets, and microservices out of the box.
Strengths: the module/controller/service architecture scales well to large teams — each feature lives in its own module with clear boundaries and explicit dependency declarations; first-party packages cover most backend needs including TypeORM, Mongoose, JWT authentication, CQRS, and Swagger documentation generation; TypeScript is required and enforced throughout, making cross-team contracts explicit. Drawbacks: nestjs/nest is a server framework, not a React data fetching tool — it produces the API that React apps consume, not React hooks; the decorator-heavy code style requires experimentalDecorators and is unfamiliar to teams coming from functional Node.js styles like Fastify bare or Hono; cold start in serverless environments can be slow due to DI container initialization.
Use nestjs/nest to build the API layer your React app fetches from. On the React side, pair it with TanStack/query for REST endpoints, or with trpc/trpc using the community NestJS adapter for end-to-end TypeScript. nestjs/nest itself is not a React data fetching library...
axios
axios
- 109,127Stars
- 20Hotness
- 89Reliability
- almost 12 yearsAge
axios/axios is a promise-based HTTP client for the browser and Node.js. Install with npm install axios, then call const res = await axios.get('/api/users') and read res.data. Unlike TanStack/query or vercel/swr, axios does not manage React state — it is a pure transport layer. It handles request and response JSON serialization automatically, serializes query parameters, supports request cancellation via AbortController, and applies timeout limits. Most teams use it as the fetcher function inside a caching library rather than calling it directly from components.
Strengths: interceptors are the killer feature — a single axios.interceptors.request.use call injects auth headers, logs requests, or retries on 401 across the entire app with no per-call boilerplate; automatic JSON serialization means axios.post('/api', { name: 'Alice' }) sends Content-Type: application/json without JSON.stringify; the instance pattern lets different parts of an app share separate base URL and auth configurations. Drawbacks: it adds a dependency the native fetch API now covers for most use cases; the bundle contributes roughly 14KB gzipped; it provides no caching, loading state, or React integration on its own — a state layer like TanStack/query is always required on top.
axios/axios is the right fetcher to pair with TanStack/query when you need interceptors, request transformation, or fine-grained per-status error handling. For simple fetch calls without interceptor needs, native fetch or sindresorhus/ky is lighter. For GraphQL, apollographql/apollo-client handles transport nativ...
openai
openai-node
- 11,050Stars
- 29Hotness
- 1Reliability
- over 4 yearsAge
openai/openai-node is the official JavaScript and TypeScript SDK for the OpenAI API. Install with npm install openai, initialize with const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }), and call await openai.chat.completions.create({ model: 'gpt-4o', messages: [...] }). The SDK handles authentication, request serialization, streaming responses via async iteration (for await (const chunk of stream)), automatic retry with exponential backoff on rate limit errors, and fully typed response shapes for every API endpoint.
Strengths: it is the canonical way to call OpenAI APIs from JavaScript — response types, streaming helpers, and error codes match the API specification exactly with no manual type definitions needed; streaming integrates cleanly with React state via an async generator that yields delta chunks; the SDK auto-retries on rate limits and transient errors with sensible defaults. Drawbacks: it must never be called directly from browser-rendered React components — the API key would be exposed to every user; it is a single-vendor SDK, not a general HTTP client; its scope is building AI features, which is one narrow use case within the broader React data fetching category.
Use openai/openai-node on the server side — a Next.js route handler, Express endpoint, or Edge Function — and stream or return results to React via TanStack/query or vercel/swr. Never import or instantiate the OpenAI client in browser-executed React code. If you need to call multiple LLM providers, the Vercel AI SDK (not in this list) provides a unified abstraction over opena...
orval-labs
orval
- 6,252Stars
- 21Hotness
- 1Reliability
orval-labs/orval is a TypeScript code generation tool that reads an OpenAPI v3 or Swagger v2 specification and generates a fully typed client. Install with npm install --save-dev @orval/core, write an orval.config.ts pointing at your spec file and configuring an output target, then run npx orval. With the React Query target enabled, Orval generates useGetUsersQuery and useCreateUserMutation hooks that drop directly into React components, along with all request and response types inferred from the spec's schemas.
Strengths: it eliminates manual TypeScript type maintenance for REST APIs — every endpoint is typed to its OpenAPI request and response schema, and regenerating after a spec change immediately surfaces breaking changes at the call site; the TanStack/query output target means generated hooks are idiomatic and cache correctly out of the box; multiple output targets (axios, fetch, zod validators, msw mocks) make it versatile. Drawbacks: it requires a well-maintained OpenAPI spec — if your API doesn't have one, generating and keeping it accurate adds upstream work; generated code is verbose and not intended to be read closely; customization via Orval's override system adds configuration complexity for non-standard API shapes.
orval-labs/orval is the right choice for teams consuming an external or separately-owned REST API that publishes an OpenAPI spec. It replaces hand-written TanStack/query wrappers and eliminates an entire class of type drift bugs. If you own both ends of the API in TypeScript within one repo, trpc/trpc is simpler — it generates no fil...
prisma
prisma
- 47,362Stars
- 40Hotness
- 50Reliability
- about 7 yearsAge
prisma/prisma is a next-generation ORM for Node.js and TypeScript. Install with npm install prisma @prisma/client, define your database schema in schema.prisma using Prisma's SDL, run npx prisma migrate dev to generate and apply a SQL migration, and query with await prisma.user.findMany({ where: { active: true }, include: { posts: true } }). Prisma generates a fully typed client from the schema at build time, so every query's return type matches your database shape exactly and TypeScript errors at compile time on missing or misspelled fields.
Strengths: generated client types eliminate database shape bugs — rename a column in the schema and every call site using the old name fails the build immediately; Prisma Migrate creates versioned, reviewable migration files automatically from schema diffs; Prisma Studio provides a browser GUI for inspecting and editing database records during development. Drawbacks: Prisma is a server-side ORM — it cannot run in the browser and is not a React data fetching tool in any sense; the Prisma engine binary adds deployment complexity in some serverless environments; for complex raw SQL queries, the query builder can feel limiting compared to Drizzle ORM or raw SQL via postgres.js.
Use prisma/prisma on the server side of a Next.js, Express, or NestJS app to query the database, then expose that data to React via trpc/trpc procedures, a REST endpoint consumed by TanStack/query, or a GraphQL resolver. Never import Prisma Client in browser-executed React code — it is a Node.js-only library with no browser support.
trpc
trpc
- 40,445Stars
- 17Hotness
- 78Reliability
- about 6 yearsAge
trpc/trpc is an end-to-end typesafe API framework for TypeScript monorepos. Instead of writing a REST API and maintaining client types separately, you define procedures on the server as TypeScript functions and call them from React with full type inference. Install with npm install @trpc/server @trpc/client @trpc/react-query, define a router with t.procedure.query(() => db.users.findMany()), and call it from a React component with trpc.users.useQuery(). The React client is powered by TanStack/query under the hood, so all caching and refetching behavior is inherited automatically.
Strengths: TypeScript infers types from server procedure to React hook with zero manual type maintenance — changing a server return type immediately errors at the call sites; useMutation return types are inferred end-to-end; the learning curve is low for teams already using TanStack/query since the hooks look nearly identical. Drawbacks: tRPC requires TypeScript on both client and server — it is incompatible with non-TypeScript backends; it is designed for monorepos where the server router type is imported directly into the client bundle, so it cannot be used when the API is owned by a separate team or service; deploying frontend and backend to different services adds complexity.
trpc/trpc is the right pick for full-stack TypeScript teams building Next.js, Remix, or similar apps where one repo owns both frontend and API. If your API is owned externally, consumed from multiple clients, or lacks TypeScript, use TanStack/query with orval-labs/orval for generated types instead.
reduxjs
redux-toolkit
- 11,226Stars
- 27Hotness
- 54Reliability
- over 8 yearsAge
reduxjs/redux-toolkit is the official, opinionated Redux package that ships with RTK Query — a data fetching and caching layer built on top of Redux. Install with npm install @reduxjs/toolkit react-redux, then define an API with createApi({ baseQuery: fetchBaseQuery({ baseUrl: '/api' }), endpoints: (build) => ({ getUsers: build.query({ query: () => '/users' }) }) }). RTK Query auto-generates useGetUsersQuery hooks and manages loading, error, and data states directly in the Redux store alongside your other application state.
Strengths: RTK Query integrates server-state caching into Redux, so teams already on Redux gain request deduplication and cache invalidation without adopting a second state library; createSlice and createAsyncThunk from redux-toolkit significantly reduce reducer boilerplate versus raw Redux; tag-based cache invalidation is explicit and traceable. Drawbacks: the bundle is larger than TanStack/query or vercel/swr; teams not already invested in Redux have little reason to adopt it — the Redux mental model adds overhead that TanStack/query avoids entirely; the generated hook naming convention (useGetUsersQuery) is verbose compared to useQuery.
reduxjs/redux-toolkit with RTK Query is the right call for teams already deeply invested in Redux who want structured data fetching without a new state library dependency. For greenfield projects with no Redux history, TanStack/query is simpler, lighter, and more focused. Do not adopt Redux specifically for its data fetching layer when TanStack/query exists.
cloudscape-design
components
- 2,614Stars
- 14Hotness
- 1Reliability
- about 4 yearsAge
cloudscape-design/components is the open-source React component library for Amazon's Cloudscape Design System — the same system used in the AWS Management Console. Install with npm install @cloudscape-design/components, import components like <Table items={users} columnDefinitions={cols} loading={isLoading} />, and they render with the AWS Console's visual style. The library includes over 60 components — tables, forms, alerts, app layout, side navigation, date pickers, and more — all built with WCAG 2.1 AA accessibility compliance and data-heavy AWS workflows in mind.
Strengths: every component is production-tested at AWS Console scale — the Table component natively handles pagination, sorting, multi-select, and server-side loading states, reducing the glue code needed to connect it to TanStack/query; accessibility is treated as a first-class requirement, not an afterthought; the consistent visual system reduces design decisions for internal tooling. Drawbacks: it is a UI component library, not a data fetching tool — it solves rendering and interaction patterns, not HTTP transport or caching; the visual style is distinctly AWS Console, making it inappropriate for consumer-facing or brand-sensitive products; adopting it means committing to Cloudscape's opinionated layout system, which is difficult to theme or override.
cloudscape-design/components is the right choice for internal admin tools, developer portals, or AWS-adjacent dashboards where the Console aesthetic is appropriate and development speed matters more than visual uniqueness. Pair it with TanStack/query ...
unjs
ofetch
- 5,333Stars
- 11Hotness
- 1Reliability
- over 5 yearsAge
unjs/ofetch is a universal fetch wrapper from the UnJS ecosystem, designed to run identically in browser, Node.js, and edge runtimes like Cloudflare Workers. Install with npm install ofetch, then call const data = await ofetch('/api/users') — JSON parsing is automatic and non-2xx responses throw typed errors. ofetch is the HTTP client used internally by Nuxt.js but is framework-agnostic and works with React. It handles retry with configurable limits, request timeout, query string serialization, and baseURL configuration.
Strengths: truly universal runtime support means a single HTTP client works in browser fetch, Node.js server-side rendering, and Cloudflare Workers without conditional imports or polyfills; automatic JSON parsing and typed error throwing reduces boilerplate; the $fetch alias familiar from Nuxt creates consistency for teams working across multiple meta-frameworks. Drawbacks: its community and ecosystem are concentrated in the Nuxt and Vue world — React-specific examples and Stack Overflow coverage are sparse; it lacks the interceptor ecosystem and battle-tested community resources of axios/axios; it is not specifically designed for React and provides no React state integration.
ofetch is a solid choice for universal TypeScript projects, edge-runtime apps, or teams who want a lightweight fetch wrapper without axios's footprint. If your project is React-first with no Nuxt influence, sindresorhus/ky or axios/axios have larger React communities. Always pair ofetch with TanStack/query or vercel/swr to add caching and React state management.
relay
- 18,948Stars
- 16Hotness
- 25Reliability
- almost 11 yearsAge
facebook/relay is Meta's GraphQL client for React, built around a compiler that processes GraphQL fragments at build time rather than runtime. Install with npm install react-relay relay-runtime, then annotate components with graphql tagged template literals. The Relay compiler analyzes your fragments statically, generates TypeScript types, and produces an optimized query plan — the runtime never sees raw GraphQL strings. Each component declares exactly the fields it needs via a fragment; Relay assembles the composite query automatically.
Strengths: compiler-enforced co-location means components declare their own data requirements and Relay assembles the composite query, eliminating prop-drilling of fetched data; the normalized store and precise fragment subscriptions keep large apps with hundreds of components efficient since only affected components re-render; Suspense integration is first-class. Drawbacks: the compilation step adds build tooling complexity that most teams find prohibitive outside Meta scale; the learning curve is the steepest of any GraphQL client; it requires a Relay-compliant GraphQL server with globally unique IDs and the Connections specification for pagination.
facebook/relay is the right pick for large-scale React and GraphQL products where per-component data precision and cache consistency across hundreds of components are critical constraints. For most teams, apollographql/apollo-client delivers GraphQL caching with far less tooling overhead. Choose Relay only when your GraphQL server is Relay-compliant and your team is prepared to invest...
apollographql
apollo-client
- 19,801Stars
- 27Hotness
- 57Reliability
- over 10 yearsAge
apollographql/apollo-client is a full-featured GraphQL client for React that manages fetching, caching, and local state. Install with npm install @apollo/client graphql, wrap your app in <ApolloProvider client={client}>, then query with const { data, loading } = useQuery(GET_USERS). Apollo Client normalizes every fetched object by __typename and id into a flat entity cache, so a user object queried in ten different components is stored once and updated everywhere when any mutation touches that entity.
Strengths: the normalized entity cache is the best available for GraphQL — a mutation response automatically propagates to every component subscribed to affected entities without manual cache key management; Apollo Devtools provides a visual explorer of every cached query and mutation; subscriptions over WebSocket are supported out of the box with useSubscription. Drawbacks: the normalized cache introduces significant complexity — cache policies, field policies, and readQuery/writeQuery APIs have a steep learning curve; bundle size at roughly 45KB gzipped is heavier than alternatives like urql; and it provides zero benefit if you're not using GraphQL.
Apollographql/apollo-client is the right choice for teams committed to GraphQL who need entity-level cache normalization. If you want a lighter GraphQL client, urql is a common alternative (not in this list). If your API is REST rather than GraphQL, pick TanStack/query — Apollo adds overhead with no corresponding benefit in a non-GraphQL stack.
jaredpalmer
formik
- 34,327Stars
- 17Hotness
- 23Reliability
- about 9 yearsAge
jaredpalmer/formik is a React form state management library that handles field values, validation, touched state, error messages, and submission lifecycle. Install with npm install formik, wrap a form in <Formik initialValues={{ email: '' }} onSubmit={handleSubmit}>, and use <Field name="email" /> for controlled inputs. Formik tracks which fields are dirty, which have been touched, and runs validation — either a custom validate function or a Yup schema via the validationSchema prop — before calling your onSubmit handler.
Strengths: it abstracts the boilerplate of controlled form inputs and validation state that would otherwise require dozens of useState calls per form; deep Yup integration via validationSchema makes schema-based validation with field-level error messages straightforward; it works with any React UI component library without coupling. Drawbacks: Formik's subscription model causes re-renders on every keystroke across the entire form tree — large forms with many fields show measurable performance degradation; react-hook-form (not in this list) has largely displaced it for new projects by using uncontrolled inputs to avoid those re-renders; Formik is in maintenance mode with a slow release cadence.
jaredpalmer/formik is reasonable for simple forms in existing projects already using it. For new projects, especially ones with large or complex forms, react-hook-form is the more performant and actively maintained choice. Formik is not a data fetching tool — pair it with TanStack/query or vercel/swr to load initial data and submit mutations to the se...
graphql
graphql-js
- 20,351Stars
- 20Hotness
- 67Reliability
- about 11 yearsAge
graphql/graphql-js is the reference JavaScript implementation of the GraphQL specification, maintained by the GraphQL Foundation. Install with npm install graphql. You define a schema with buildSchema(sdl) or the type builder API, execute queries against it with graphql({ schema, source, rootValue }), and typically expose it over HTTP via a middleware like graphql-http. It validates queries against the schema before execution, returning structured errors for type mismatches, unknown fields, or argument violations. All major Node.js GraphQL server frameworks depend on it as a peer dependency.
Strengths: it is the authoritative GraphQL runtime for JavaScript — Apollo Server, graphql-yoga, and graphql-tools all run on top of it, so understanding graphql-js is understanding the foundation; query validation against the schema catches type errors at execution time; it is peer-reviewed against the GraphQL specification and updated as the spec evolves. Drawbacks: graphql-js is a server-side library — React apps consuming a GraphQL API do not use it directly; using it directly means building your own server layer rather than using a higher-level framework; it has no built-in HTTP transport, subscriptions support, or persisted query handling — those require additional packages.
Use graphql/graphql-js as the base runtime when building a custom GraphQL server in Node.js. For serving GraphQL in production, layer it under Apollo Server or graphql-yoga. For fetching GraphQL data in React components, use apollographql/apollo-client or facebook/relay — graphql-js itself is a serv...
pmndrs
valtio
- 10,210Stars
pmndrs/valtio is a proxy-based state management library for React and vanilla JavaScript. Install with npm install valtio, create a store with const state = proxy({ count: 0, user: null }), and read it in any component with const snap = useSnapshot(state). Mutations are plain JavaScript assignments — state.count++ or state.user = fetchedUser — and Valtio's Proxy wrapper intercepts those assignments to notify subscribers and trigger re-renders only in components that accessed the changed path.
Strengths: mutation syntax is the most natural of any React state library — no reducers, no immer, no dispatch, just object assignment; the derive utility creates computed values that update automatically when their dependencies change; it works without a provider, making it easy to share state between unrelated component trees or use from outside React. Drawbacks: the Proxy approach behaves unexpectedly with non-serializable values like class instances, Maps, and Sets; because state is global and mutable, it requires discipline to prevent accidental cross-feature state pollution; it provides none of the request lifecycle features — loading flags, error states, caching, background revalidation — that TanStack/query handles automatically.
Pick pmndrs/valtio for client-side UI state such as modals, sidebar filters, theme preferences, or multi-step wizard progress — not for server data. Always pair it with TanStack/query or vercel/swr for the server-data layer. If your primary need is data fetching rather than client state, valtio is the wrong tool entirely.
elbywan
wretch
- 5,178Stars
elbywan/wretch is a small wrapper around the native fetch API with a chainable, fluent interface. Install with npm install wretch, then call wretch('/api/users').get().json() to fetch and parse JSON. The chainable design eliminates the two-step fetch().then(r => r.json()) pattern. wretch is framework-agnostic and runs in browsers, Node.js, and Deno. It supports middleware for logging, authentication, and retry logic, and provides typed per-status error catching: .unauthorized(err => redirect('/login')) and .badRequest(err => showToast(err)) as named chain methods.
Strengths: the fluent API is genuinely more readable than raw fetch — wretch('/api').auth('Bearer ' + token).post(body).json() fits on one line and reads left to right; typed per-status error handlers reduce the boilerplate of checking response.status manually; it is tiny at under 3KB gzipped with zero dependencies. Drawbacks: its community is significantly smaller than axios/axios and sindresorhus/ky — fewer examples, fewer Stack Overflow answers, and fewer third-party middleware packages; it provides no caching, loading state, or React integration, so TanStack/query or vercel/swr is still required; documentation coverage is lighter than competitors.
Pick elbywan/wretch if you prefer a fluent chaining API to axios's config-object style and want the smallest possible transport dependency. It works well as the fetcher inside vercel/swr or TanStack/query. For teams already using axios with a mature interceptor setup, the switching cost is unlikely to be worth it.
