I’m adopting react-router-dom
for a production app and I’m wondering if it makes sense to switch all of the links for internal routes (for example on our navbar, etc.) from the native a
tag to the Link
tag provided by react-router-dom
. I tried measuring the performance of this change but empirically found no difference. Am I misunderstanding something about how Link
differs from a
? Is there a strong reason to change? If so what are they and what metrics should I be looking at?
Question posted in Javascript
A very good W3school tutorial can be found here.
A very good W3school tutorial can be found here.
2
Answers
The key benefit of
<Link>
in a React application over the native<a>
tag is that it supports client-side routing and supports SPA behavior. The application state is preserved and entire page reloads are avoided when you use<Link>
to define internal links within your application. React Router manages navigation and changes only the necessary components.One is a React component, the
Link
, while the other is an HTML element, the anchor tag. TheLink
component renders an anchor tag to the DOM, so from the DOM’s perspective, they are identical.Perhaps so. The
Link
component, andreact-router
in general, is specific to client-side routing and navigation. Instead of making a network request to a server for a specific page/file,react-router
intercepts the call and handles the routing/navigation entirely on the client.Strong reason? This is a bit subjective. All React apps are effectively Single Page Applications (SPAs). Using
react-router
allows React SPAs to fake being a Multiple Page Application. If you also wish to keep and maintain any local state, then yes, very strong reason to to change and use client-side routing. Anchor tags make a request to a server and will reload the page. If you are using raw anchor tags to navigate through your multi-page React app you are making unnecessary server requests to fetch the same app bundle(s) repeatedly.Basically if you are wanting to create different pages for users of your app to view then using a client-side routing/navigation library is what you’ll want.