3 ms·
Sneaky React Memory Leaks II: Closures vs. React Query
- deleted 2y ago[deleted]
- SebastianKra 2y agoAnother solution, apart from custom hooks is the queryOptions helper function: 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/typescript#typing-query-options 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.