T
TanStack3d ago
xenial-black

React best practices (context vs hook)

Is there an accepted or recommended best practice when it comes to reusing collection/mutation logic with TanStack DB and React? For instance, while migrating my app from Query to DB, I wrote this at first:
export const useBlock = (id: string) => {
const { blocks } = useCollections(); // defines all my collections
const query = useLiveQuery((q) =>
q
.from({ block: blocks })
.where(({ block }) => eq(block.id, id))
.findOne()
);

return {
block: query.data,
updateTitle: (title: string) =>
blocks.update(id, (draft) => {
draft.title = title;
}),
};
};
export const useBlock = (id: string) => {
const { blocks } = useCollections(); // defines all my collections
const query = useLiveQuery((q) =>
q
.from({ block: blocks })
.where(({ block }) => eq(block.id, id))
.findOne()
);

return {
block: query.data,
updateTitle: (title: string) =>
blocks.update(id, (draft) => {
draft.title = title;
}),
};
};
Now I'm trying to understand whether the hook is a good enough approach or if a context is better since I'll be using this useBlock hook in a variety of places. Does useLiveQuery already optimize for that under the hood?
2 Replies
stormy-gold
stormy-gold3d ago
You should generally reuse collections to avoid reloading data etc There's a small cost to setting up new live queries (generally at most a ms or so) but it doesn't hurt to reuse them for sure
xenial-black
xenial-blackOP3d ago
oh yeah forgot to mention useCollections does pull from a context. might as well put live queries in relevant contexts too. thanks!

Did you find this page helpful?