TanStackT
TanStack3mo ago
7 replies
slow-yellow

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;
      }),
  };
};


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?
Was this page helpful?