In React, routing refers to the process of handling navigation between different parts of the application. The way routing is handled can differ depending on the version of React you are using.
- React v16.3 and below: In versions of React prior to v16.4, routing was typically handled using third-party libraries such as React Router. For example, in React v16.3, you could use React Router v4 to handle routing like this:
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
function App() {
return (
<Router>
<div>
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/contact">Contact</Link>
</nav>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</div>
</Router>
);
}
- React v16.4 and above: Starting with React v16.4, React introduced a new feature called React Router Hooks, which allows for handling routing using hooks instead of higher-order components. Here’s an example of how to handle routing using React Router Hooks:
import { useRoutes, A } from 'hookrouter'
const routes = {
'/': () => <Home />,
'/about': () => <About />,
'/contact': () => <Contact />
}
function App() {
const routeResult = useRoutes(routes)
return (
<div>
<nav>
<A href="/">Home</A>
<A href="/about">About</A>
<A href="/contact">Contact</A>
</nav>
{routeResult}
</div>
)
}
It’s important to note that React Router Hooks is not a standalone library, but rather a feature built into React itself.
Another option for handling routing in React 16.4 and above is the use of Suspense which allows you to load the components lazily or asynchronously.
It is always recommended to use the latest version of React to take advantage of the new features and improvements. However, you can use any version of React that suits your project’s needs, and use the routing methods that are compatible with that version.