Getting started with Routing using Hooks

Abhishek Gautam
5 min readJan 27, 2021

Introduction

Since hooks were introduced in React a lot of things have changed from the conventional approach. Due to the capabilities of Hooks, we have redefined how we used to approach certain concepts in React. The intent of this post is to explore possibilities for improving routing experience using Hooks. Here we will be talking about React Router and HookRouter modules.

React Router

It’s a very popular declarative way of routing in react. It takes away the pain of manually setting and configuring routes for all pages. It uses 3 major components to help achieve this — Route, Link, BrowserRouter

Routing in React Router

To define a route in a react app we would have to import <Route /> component from React Router Package takes in two props, the path to direct the user to the specified path and component to define the content of the configured path.

import Users from “./components/Users”;import Contact from “./components/Contact”;import Home from “./components/Home”;function App() {return (<div>  <Router>    <div>      <Route path=”/Home” component={Home} />      <Route path=”/Users” component={Users} />      <Route path=”/Contact” component={Contact} />   </div>  </Router></div>); }

The Hooks alternative for routing

For this, we will be using the hook router package that we will be using. It exports a useRoutes() hook which evaluates a pre-defined route object and returns a result. While defining the route object, the routes are defined as keys having values as a function that will be invoked when the route matches.

import React from "react";import Users from "./components/Users";import Contact from "./components/Contact";import Home from "./components/Home";const routes = {"/Users": () => <Users />,"/Home": () => <Home />,"/contact": () => <Contact />};export default routes;

With react-router, we have to render the <Route /> component for all our individual routes present in our application. Now once we have defined our routes object we can simply pass it to the useRouter() hook to enable routing in our application.

import {useRoutes} from 'hookrouter';import Routes from './router'function App() {const routeResult = useRoutes(Routes)return routeResult}

Navigation in React Router

React router exports as Link component which helps us customize route navigations and manage routing in our react app. Now let’s see the code snippet for rendering routes on screen and navigate to them when clicked.

import { Route, Link, BrowserRouter as Router } from "react-router-dom";import Users from "./components/Users";import Contact from "./components/Contact";import Home from "./components/Home";function App() {return (<div className="App">  <Router>    <div>      <ul>        <li> <Link to="/Home">Home</Link></li>        <li><Link to="/Users">Users</Link></li>        <li><Link to="/Contact">Contact</Link></li>      </ul>      <Route path="/Home" component={Home} />      <Route path="/Users" component={Users} />      <Route path="/Contact" component={Contact} />    </div>  </Router></div>); }

Navigation using Hooks

The hook router module provides a wrapper around the HTML anchor tag as <A />. This is available as a react component and is 100% feature compatible with native <a />. The difference is that it pushes the navigation to then the history stack.

const routes = {"/User": () => <Users />,"/Home": () => <Home />,"/Contact": () => <Contact />};function App() {const routeResult = useRoutes(routes);return (<div className="App">  <A href="/User">Users Page</A>  <A href="/Home">Home Page</A>  <A href="/Contact">Contacts Page</A>    {routeResult}</div>); }

Programmatic Navigation

Hooksrouter modules export navigate() method to which we can pass the URL to which we want to navigate to. Every navigation through the navigate method allows forward navigation which means that the user can click the browser’s back button to return to the previous URL. This is the configured default behavior but if want to replace the navigation then we can use the navigation() method which replaces the current history entry and creates a new record.

React Router Switch

Usually switch is used to render a default route or load the first matching route. To do this all routes are wrapped inside the <Switch /> component.

import Users from "./components/Users";import Contact from "./components/Contact";import Home from "./components/Home";import NoPageFound from "./components/NoPageFound.js";function App() {return (<div className="App">  <Router>    <div>     <ul>       <li><Link to="/">Home</Link></li>       <li><Link to="/users">Users</Link></li>       <li><Link to="/contact">Contact</Link></li>    </ul>   <Switch>     <Route exact path="/" component={Home} />     <Route path="/Users" component={Users} />     <Route path="/Contact" component={Contact} />     <Route component={NoPageFound} />  </Switch> </div></Router></div> ); }

Hooks alternative to Switch

Because we define a routes object that holds all our route paths, and simply pass that object into the useRoutes() Hook, it becomes really straightforward to conditionally render routes. If we define a NoPageFound file to render by default when a selected route is not defined, we’ll only need to pass that file for rendering alongside our result function like so:

import { useRoutes, A } from "hookrouter";import routes from "./router";import NoPageFound from "./components/NoPageFound";function App() {const routeResult = useRoutes(routes);return (<div className="App">  <A href="/user">Users Page</A> <br />  <A href="/about">About Page</A>  <br />  <A href="/contact">Contacts Page</A> <br />    {routeResult || <NoPageFound />}</div> ); }

Redirects in React Router

This is useful when we want the user to dynamically go to a particular page from a requested route. For example, when the user login is successful they can be sent to some landing page from the current user page.

In React router the same can be achieved using the history object or <Redirect /> component.

import React from 'react'class Login extends React.Component {loginUser = () => {// if (user is logged in successfully)this.props.history.push('/dashboard')}render() {return (<form>  <input type="name" />  <input type="email" />  <button onClick={this.loginUser}>Login</button></form>)}}export default Login

Hooks alternative to Redirect

The hookrouter module exports useRedirect() hook that can take a source and a target routeuseRedirect('/Login, '/dashboard');import {useRoutes, useRedirect} from 'hookrouter';import dashboard from "./components/Dashboard";const routes = {'/home': () => <Users />,'/dashboard': () => <Dashboard />};const Users = () => {useRedirect('/user', '/dashboard');const routeResult = useRoutes(routes);return routeResult}

It is important to note that useRedirect() triggers a replacement navigation intent. So the navigation history will be replaced with a new history object with a single entry.

Handing Route params in React Router

This comes very useful when we want to load components dynamically based on URLs. To do this we will need to pass URL parameters by simply passing it as a placeholder starting with a colon.

<Route path="users/:id" component={Users} />

Hooks alternative to the handling URL parameter

Hookrouter treats URL parameters as compared to React Router. The construct is the same as compared to React Router. Hooks read all params and stores them in an object using the key defined in routing. Then all the named parameters will be forwarded to your route result function as a combined object.

const routes = {'/user/:id': ({id}) => <User userId={id} />}

Conclusion

React router is the great and conventional way of handling routing in React but with the introduction of hooks in react things have changed. Hookrouter is based on hooks and offers a more flexible and cleaner way of defining the routes in smaller projects. If you are in the exploratory phase of choosing a router package for your app I would definitely encourage you to try this.

Feel free to learn more about the hook router module here

--

--

Abhishek Gautam

A tech geek who loves to solve problems and coming up with meaningful, simplistic solutions.