Search code examples
reactjsreact-routerreact-router-domrtk-query

What is the difference between BrowserRouter and createBrowserRouter in react-router v6? Can I use createBrowserRouter without using data APIs?


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.


Solution

  • 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.