13

I have read this in the documentation but I am not sure what the difference between BrowserRouter and createBrowserRouter.

This is what it says in docs:

createBrowserRouter:

This is the recommended router for all React Router web projects. It uses the DOM History API to update the URL and manage the history stack.

It also enables the v6.4 data APIs like loaders, actions, fetchers and more.

BrowserRouter:

A <BrowserRouter> stores the current location in the browser's address bar using clean URLs and navigates using the browser's built-in history stack.

My second question is:

Can I use createBrowserRouter without adding data APIs like loaders, actions etc. The reason is I am not sure how to use data APIs with Redux Toolkit Query and I found limited sources. I could perhaps add loaders later.

Yazan Qarabash
  • 155
  • 1
  • 8

2 Answers2

7

The difference really is just about as simple as being able to use the Data APIs, e.g. loaders, actions, and a whole host of data-router-only hooks and utility functions (currently designated by a "new" icon in the docs).

Can I use createBrowserRouter without adding data APIs like loaders, actions etc.

Yes, absolutely you can. There's nothing forcing you (at this moment) to use the new data routers and the Data APIs.

From what I can tell there's some overlap between what loading data and submitting data via route loaders and actions and what Redux-Toolkit/Query provides, but that about the extent of the similarity, data fetching. So far I don't see the Data APIs as a 1-to-1 replacement for redux data caching.

Loaders and actions seem to be useful if the data being fetch is only relevant to a specific React component, or a subtree of routes, whereas Redux is a global state management library and any action can be dispatched from anywhere and the store can be read from anywhere.

If you've already an app using Redux, RTK, and RTK-Query, then I think the loaders/actions will feel a bit underwhelming and clunky. This is at least my opinion/experience of them so far. That said, the Data APIs are relatively new and perhaps just haven't found their niche in the React world just yet. For example, I think it's the case that RRD Data APIs likely work well and shine when applied on Server Side Rendering, i.e. Remix, the maintainers of the react-router libraries.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • Still a bit unclear. So you are unable to use e.g. `loader` or `action` if you nest `Route` element within a `BrowserRouter`? As opposed to using `createBrowserRouter`? – sherrellbc Jul 05 '23 at 01:06
  • @sherrellbc Affirmative, since `BrowserRouter` isn't a "Data Router", none of the data APIs will be available. – Drew Reese Jul 05 '23 at 15:15
0

One major difference would be in blocking navigation. BrowserRouter doesn't support unstable_useBlocker (it will prompt useBlocker must be used within a data router feature warning). You'd need to use RouterProvider instead.

Ilfatus
  • 31
  • 3