Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

overview.md

138 lines6.5 KB

1---
2id: overview
3title: Overview
4---
5​
6Solid Query is the official SolidJS adapter of TanStack Query that makes **fetching, caching, synchronizing and updating server state** in your web applications a breeze.
7​
8## Motivation
9​
10SolidJS has been gaining popularity as a fast, reactive, and declarative library for building user interfaces. It comes packed with a lot of features out of the box. Primitives like `createSignal`, `createStore` are great for managing client state. And, unlike other UI libraries, SolidJS has strong opinions about managing asynchronous data. The `createResource` API is a great primitive for handling server state in SolidJS apps. A `resource` is a special kind of signal that can be used to trigger `Suspense` boundaries when the data is in a loading state.
11​
12```tsx
13import { createResource, ErrorBoundary, Suspense } from 'solid-js'
14import { render } from 'solid-js/web'
15​
16function App() {
17 const [repository] = createResource(async () => {
18 const result = await fetch('https://api.github.com/repos/TanStack/query')
19 if (!result.ok) throw new Error('Failed to fetch data')
20 return result.json()
21 })
22​
23 return (
24 <div>
25 <div>Static Content</div>
26 {/* An error while fetching will be caught by the ErrorBoundary */}
27 <ErrorBoundary fallback={<div>Something went wrong!</div>}>
28 {/* Suspense will trigger a loading state while the data is being fetched */}
29 <Suspense fallback={<div>Loading...</div>}>
30 <div>{repository()?.updated_at}</div>
31 </Suspense>
32 </ErrorBoundary>
33 </div>
34 )
36​
37const root = document.getElementById('root')
38​
39render(() => <App />, root!)
40```
41​
42This is amazing! In a few lines of code, you can fetch data from an API and handle loading and error states. But, as your application grows in complexity, you will need more features to manage server state effectively. This is because **server state is totally different from client state**. For starters, server state:
43​
44- Is persisted remotely in a location you do not control or own
45- Requires asynchronous APIs for fetching and updating
46- Implies shared ownership and can be changed by other people without your knowledge
47- Can potentially become "out of date" in your applications if you're not careful
48​
49Once you grasp the nature of server state in your application, **even more challenges will arise** as you go, for example:
50​
51- Caching... (possibly the hardest thing to do in programming)
52- Deduping multiple requests for the same data into a single request
53- Updating "out of date" data in the background
54- Knowing when data is "out of date"
55- Reflecting updates to data as quickly as possible
56- Performance optimizations like pagination and lazy loading data
57- Managing memory and garbage collection of server state
58- Memoizing query results with structural sharing
59​
60This is where **Solid Query** comes in. The library wraps around `createResource` and provides a set of primitives and utilities to manage server state effectively. It works amazingly well **out-of-the-box, with zero-config, and can be customized** to your liking as your application grows.
61​
62On a more technical note, Solid Query will likely:
63​
64- Help you remove **many** lines of complicated and misunderstood code from your application and replace with just a handful of lines of Solid Query logic.
65- Make your application more maintainable and easier to build new features without worrying about wiring up new server state data sources
66- Have a direct impact on your end-users by making your application feel faster and more responsive than ever before.
67- Potentially help you save on bandwidth and increase memory performance
68​
69## Enough talk, show me some code already!
70​
71In the example below, you can see Solid Query in its most basic and simple form being used to fetch the GitHub stats for the TanStack Query GitHub project itself:
72​
73```tsx
74import {
75 useQuery,
76 QueryClient,
77 QueryClientProvider,
78} from '@tanstack/solid-query'
79import { ErrorBoundary, Suspense } from 'solid-js'
80​
81function App() {
82 const repositoryQuery = useQuery(() => ({
83 queryKey: ['TanStack Query'],
84 queryFn: async () => {
85 const result = await fetch('https://api.github.com/repos/TanStack/query')
86 if (!result.ok) throw new Error('Failed to fetch data')
87 return result.json()
88 },
89 staleTime: 5 * 60 * 1000, // 5 minutes
90 throwOnError: true, // Throw an error if the query fails
91 }))
92​
93 return (
94 <div>
95 <div>Static Content</div>
96 {/* An error while fetching will be caught by the ErrorBoundary */}
97 <ErrorBoundary fallback={<div>Something went wrong!</div>}>
98 {/* Suspense will trigger a loading state while the data is being fetched */}
99 <Suspense fallback={<div>Loading...</div>}>
100 {/*
101 The `data` property on a query is a SolidJS resource
102 so it will work with Suspense and transitions out of the box!
103 */}
104 <div>{repositoryQuery.data?.updated_at}</div>
105 </Suspense>
106 </ErrorBoundary>
107 </div>
108 )
110​
111const root = document.getElementById('root')
112const client = new QueryClient()
113​
114render(
115 () => (
116 <QueryClientProvider client={client}>
117 <App />
118 </QueryClientProvider>
119 ),
120 root!,
122```
123​
124## Well, that seems like more lines of code to do the same thing?
125​
126Yes it is! But, these few lines of code unlock a whole new world of possibilities. In the example above, your query is cached for 5 minutes, meaning that if a new component mounts anywhere in your app that uses the same query within 5 minutes, it will not re-fetch the data but instead use the cached data. This is just one of the many features that Solid Query provides out of the box. Some other features include:
127​
128- **Automatic Refetching**: Queries automatically refetch in the background when they become "stale" (out of date according to the `staleTime` option)
129- **Automatic Caching**: Queries are cached by default and shared across your application
130- **Request Deduplication**: Multiple components can share the same query and make one request
131- **Automatic Garbage Collection**: Queries are garbage collected when they are no longer needed
132- **Window Focus Refetching**: Queries automatically refetch when the application comes back into focus
133- **Pagination**: Built-in support for pagination
134- **Request Cancellation**: Automatically cancels outdated or unwanted requests
135- **Polling/Realtime**: It's easy to add polling or realtime updates to your queries with a simple `refetchInterval` option
136- **SSR Support**: Solid Query works great with server-side rendering
137- **Optimistic Updates**: Easily update your cache with optimistic updates
138- **And much more...**