createBrowserRouter
inside component
#10440
-
Does using Poking around the source code, it appeals to me that it is not possible, but the docs doesn't mention anything, that this would be against the implementation details. An example, having const App = () => {
const [foo, setFoo] = useState("");
const router = createBrowserRouter([
{
path: "/",
element: <Foo foo={foo} />,
},
{
path: "/profile",
element: <Profile foo={foo} setFoo={setFoo} />,
},
])
return <RouterProvider router={router} />
}; |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 5 replies
-
We should probably make this more clear in the docs (PR's welcome!) but the intention is that your router is a singleton for your application as shown in the docs. If you are doing it inside a react component then you end up creating a new router anytime that component re-renders which will blow away any old state of the router. Instead, you can setup or create contexts in your App component or a root layout component, and then access them from inside your route components. You cannot leverage context in loaders and actions since that breaks the decoupling of fetching and rendering which is at the core of the 6.4+ data API design. |
Beta Was this translation helpful? Give feedback.
-
Hello, how would i use a Context.Provider that wraps all my routes, when using createBrowserRouter? |
Beta Was this translation helpful? Give feedback.
-
I have a question, what if my auth provider needs the navigate? and the router needs to know what is the user type to render a route or not. I could do the layout, but then I cannot access my authProvider to know which element/component to render, based on the user type. They kinda depend on each other, with BrowserRoute that was not a problem, because it was wrapping all the componentes, including the Routes component, so I could acess user information to render conditionally. Is there a way I can force a refresh when logging ? |
Beta Was this translation helpful? Give feedback.
We should probably make this more clear in the docs (PR's welcome!) but the intention is that your router is a singleton for your application as shown in the docs. If you are doing it inside a react component then you end up creating a new router anytime that component re-renders which will blow away any old state of the router.
Instead, you can setup or create contexts in your App component or a root layout component, and then access them from inside your route components. You cannot leverage context in loaders and actions since that breaks the decoupling of fetching and rendering which is at the core of the 6.4+ data API design.