TanStackT
TanStack9mo ago
55 replies
brilliant-lime

Hooks proposal

I have written 2 hooks that we've been finding pretty useful at work, I was wondering whether they might be of interest to the community. They're fully type-safe like native tanstack/router hooks (except for route masking because we don't use that, but that's seems doable if needed).

The first is useNavigatePreload, it works like
useNavigate
, but in 2 steps, first to preload, then to actually navigate.
const preload = useNavigatePreload()
const { mutate } = useMutation({ ... })
const onSubmit = (data) => {
  const navigate = preload('/foo/$id')
  mutate(data, {
    onSuccess: () => navigate({ id: 123 })
  })
}

Here, we need to navigate programmatically because it needs to happen after a "code event" (a mutation here), and not a "user action" (where we would use a regular link). But we still want some preloading. So the preload() call will do a router.loadRouteChunk under the hood (not actually call the loaders, because the mutation is likely to change things in the destination route). Having
navigate
tied to preload ensures we preload the correct route.

The second is useSearchState. It's based on useSearch but behaves like a
useState
.
const [value, setValue] = useSearchState({
  from: '/foo',
  key: 'bar',
})
return <button onClick={() => setValue(v => v + 1)} />

This hook makes it very easy to manipulate search params in a way that is familiar to react devs. It also batches calls to the setState into a single
navigate
call to minimize work by the router.

I can provide the actual implementation if someone wants either of those. Or maybe seeing the idea is helpful enough to someone.
Was this page helpful?