TanStack / TanStack/router

`Route.useRouteContext()` returns an empty object instead of null

Open
#7,110 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
TypeScript
Stars
15.1k
Forks
1.9k
Avg merge
1d 20h
Merged PRs (30d)
143

Description

Which project does this relate to?

Router

Describe the bug

As the title says, the Route.useRouteContext() function returns an empty object instead of null when defining beforeLoad to return null, regardless if it's a server function or not. The same behaviour does not occur with the loader and Route.useLoaderData functions. The type for Route.useRouteContext is correct however.

Your Example Website or App

https://codesandbox.io/p/devbox/2lylk3

Steps to Reproduce the Bug or Issue
  1. Go to the reproduction link.
index.tsx:
import { createFileRoute } from "@tanstack/react-router";
import { createServerFn } from "@tanstack/react-start";

export const foo = createServerFn({ method: "GET" }).handler(() => null);

export const Route = createFileRoute("/")({
  beforeLoad: async () => await foo(),
  component: Home,
  loader: async () => await foo(),
});

function Home() {
  const state1 = Route.useRouteContext();
  const state2 = Route.useLoaderData();
  console.log("state1", state1, !!state1);
  console.log("state2", state2, !!state2);

  return <p>Hi</p>;
}
  1. Check the terminal output.
state1 {} true
state2 null false
state1 {} true
state2 null false
Expected behavior

Route.useRouteContext should return null.

Screenshots or Videos

No response

Platform
  • Router / Start Version: 1.168.10 / 1.167.16
  • OS: Linux
  • Browser: Firefox (Zen)
  • Browser Version: 1.19.5b (Zen)
  • Bundler: Vite
  • Bundler Version: 8.0.5
Additional context

I am using TanStack Start but that shouldn't matter.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the supplied index.tsx reproduction in the linked CodeSandbox and run it to confirm the differing beforeLoad/useRouteContext and loader/useLoaderData results. Trace how Route.useRouteContext handles a beforeLoad value of null, compare it with the loader path, and consider the issue done when the hook returns null in the reproduction.

Written by the indexing model from the issue text.

Assessment

Tech stack
react, typescript, vite
Domain
frontend, web-dev
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
65/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.