A New Approach to Routing in React
What is React Router?
React Router is a declarative way of managing routes in React applications. It provides a simple and efficient way to navigate between different views in an application.
When to Use React Router
React Router is a good choice for large and complex applications with multiple navigational requirements. It’s also well-suited for React Native applications. However, for smaller applications with simple routing needs, a more lightweight solution may be sufficient.
Introducing HookRouter
HookRouter is a Hooks-based module that provides a simple and flexible way of handling routes in React applications. It’s designed for smaller applications and offers a more lightweight alternative to React Router.
Basic Routing with HookRouter
To get started with HookRouter, you need to define your routes as an object with keys representing the route paths and values representing the components to render. You can then use the useRoutes
Hook to evaluate the current route and render the corresponding component.
import { useRoutes } from 'hookrouter';
const routes = {
'/': () => <Home/>,
'/about': () => <About/>,
};
function App() {
const result = useRoutes(routes);
return result;
}
Navigation with HookRouter
HookRouter provides a useRedirect
Hook that allows you to redirect users to a different route. You can also use the navigate
function to programmatically navigate to a different route.
import { useRedirect, navigate } from 'hookrouter';
function App() {
useRedirect('/old-path', '/new-path');
return <div>
<a href="#" onClick={() => navigate('/new-path')}>Go to new path</a>
</div>;
}
Handling URL Parameters
HookRouter allows you to handle URL parameters using a colon followed by the parameter name. You can then access the parameter value using the useParams
Hook.
import { useParams } from 'hookrouter';
const routes = {
'/users/:id': ({ id }) => <User id={id} />,
};
function User({ id }) {
return <div>
<strong>User {id}</strong>
</div>;
}