Skip to content

🗺️ Client side router context #14055

@brophdawg11

Description

@brophdawg11

Discussed in #9856

Originally posted by jamesopstad September 22, 2022

What is the new or updated feature that you are suggesting?

It would be useful to be able to set a context value when initialising the router that can then be accessed in loaders and actions.

Example

// main.jsx
const queryClient = new QueryClient();

const router = createBrowserRouter(
  [
    {
      path: '/',
      element: <Root />,
      loader: rootLoader
    }
  ],
  {
    context: {
      queryClient
    }
  }
);

// root.jsx
export async function loader({ params }, context) {
  return await context.queryClient.fetchQuery(query);
}

Why should this feature be included?

As loaders and actions cannot use React hooks, there is currently no way to access contextual data within them. A workaround suggested in this article (https://tkdodo.eu/blog/react-query-meets-react-router) is to create an additional function wrapper for each loader and action. Providing a context value directly when initialising the router would be a more elegant solution.

Metadata

Metadata

Assignees

Type

No type

Projects

Status

Stage 4 - Stabilization

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions