Sneaky React Memory Leaks II: Closures vs. React Query
schiener.io
schiener.io
function postQuery(id: number) {
return queryOptions({
queryKey: ["posts", id],
queryFn: () => fetchPost(String(id))
})
}
function App() {
const [id, setId] = useState(1);
const { data, error, isPending } = useQuery(postQuery(id))
}
See https://tanstack.com/query/latest/docs/framework/react/types...In addition to fixing this leak, it has several advantages:
- It DRYs the QueryKey
- In Typescript, it tags the QueryKey with the return type, giving you type safety in utility functions such as setQueryData
- Unlike custom hooks, it gives you more flexibility if you want to use useSuspenseQuery, useQueries or if you want to prefetch the query.