创建查询抽象

Photo by Earl Wilcox

照片由 Earl Wilcox 提供

Developers love creating abstractions. We see some code that we’ll need in a different place - abstraction. Need this 3-liner, but slightly different - abstraction (with a flag). Need something that every useQuery should do - Create an aBsTrAcTiOn!

开发者喜欢创建抽象。我们看到一些将在不同地方需要的代码 - 抽象。需要这个 3 行代码,但略有不同 - 抽象(带一个标志)。需要每个 useQuery 都应该做的事情 - 创建一个 aBsTrAcTiOn!

There’s nothing wrong with abstractions per se, but they have tradeoffs, like everything else. Dan’s talk The wet codebase (opens in a new window) is among one of my favourite talks ever, and he explains this really well.

抽象本身并没有问题,但它们也有权衡取舍,就像其他一切一样。Dan 的演讲 The wet codebase (在新窗口中打开) 是我有史以来最喜欢的演讲之一,他解释得非常好。

In React, creating abstractions very often correlates with custom hooks. They are great for sharing logic between multiple components, or even just hiding that gnarly useEffect behind a good name. For the longest time, creating your own abstraction over useQuery meant writing a custom hook:

在 React 中,创建抽象通常与自定义钩子相关联。它们非常适合在多个组件之间共享逻辑,甚至只是将那个棘手的 useEffect 隐藏在一个好名字后面。很长一段时间里,创建自己的 useQuery 抽象意味着编写一个自定义钩子:

function useInvoice(id: number) { queryKey: ['invoice', id], queryFn: () => fetchInvoice(id),const { data } = useInvoice(1)

This is straightforward, and I can now call useInvoice() wherever I want instead of having to repeat the queryKey and queryFn all the time. It ensures consistency for the queryKey, which could otherwise lead to duplicate cache entries. And because it just returns what useQuery returns, we have an interface that is aligned with TanStack Query’s API surface, so there’s no surprise naming where this hook is used.

这很直接,现在我可以在任何地方调用 useInvoice(),而不用每次都重复 queryKeyqueryFn。它确保了 queryKey 的一致性,否则可能会导致重复的缓存条目。而且因为它只是返回 useQuery 返回的内容,我们有一个与 TanStack Query 的 API 表面对齐的接口,所以在使用这个 Hook 时不会有意外的命名。

Types are also fully inferred, because we don’t annotate any generics manually anywhere, which is great. The more our TypeScript code looks like plain JavaScript, the b...

开通本站会员,查看完整译文。

inicio - Wiki
Copyright © 2011-2026 iteam. Current version is 2.155.0. UTC+08:00, 2026-03-06 18:26
浙ICP备14020137号-1 $mapa de visitantes$