Skip to content

[Feature]: Router Context #9324

Closed
Closed
@jamesopstad

Description

@jamesopstad

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

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions