• Hookrouter: A Modern Approach to React Routing
  • Isuri Devindi
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: Zz Zhaojin
  • Proofread: PassionPenguin, KimYang

Modern use of the React route Hookrouter

Routing is critical to navigate and initialize state in a single page application (SPA) page. For React, most developers have used the React-router-dom, which is a variable used by the Reactrouter library for routing.

However, with the introduction of React hooks, a new module called Hookrouter has recently been introduced as a flexible, fast route based on hooks.

This article focuses on how we used the Hookrouter module to implement the basic functionality of Reactrouter.


To demonstrate Hookrouter’s capabilities, I’ll use as an example a mall with four basic components, namely nav.js, home.js, about.js, and shop.js. In addition, the full React application that uses Hookrouter as a route can be found here.

1. Hookrouter and Reactrouter define route comparison

When using Reactrouter, we can define the route as follows.

import Nav from './components/Nav';
import About from './components/About';
import Shop from './components/Shop';
import Home from './components/Home';
import {BrowserRouter as Router,Route} from'react-router-dom';

function App() {  
  return (    
    <Router>
    <div className="App">
      <Nav/>
      <Route path = '/'  component = {Home}/>
      <Route path = '/about' component = {About}/>
      <Route path = '/shop' component = {Shop}/>             
    </div>
   </Router>
  );
}
export default App;
Copy the code

I hope you’re all familiar with these relatively simple examples.

If we use Hookrouter for implementation, we can declare the route as an object using useRoutes() hook.

The key of the object defines the path, and the value of the object is the function that fires when the path matches. The router checks the paths one by one and stops when it finds a match.

import {useRoutes} from 'hookrouter'
import Nav from './components/Nav';
import About from './components/About';
import Shop from './components/Shop';
import Home from './components/Home';

function App() {
  const routes = {
    '/' :() = ><Home/>.'/about' :() = > <About/>.'/shop' :() = > <Shop/>};const routeResults = useRoutes(routes);
  return (
    <div className="App">
        <Nav/>
        {routeResults}
    </div>
  );
}

export default App;
Copy the code

The
component in Reactrouter must be rendered each time, along with all props for each Route in the application. However, in Hookrouter, routes defined as objects can simply be passed to useRoutes() hooks.

Note: Ensure that routing objects are created outside of the component; Otherwise, the entire object will be recreated each time it is rendered.

2. Hookrouter implements the Reactrouter switch function


is used to render routes and only render the first child

or

that matches the location.

is often used to render 404 pages when defined navigation routes do not match.



Let’s look at how to render a 404 page with a Reactrouter route using

.

import Nav from './components/Nav';
import About from './components/About';
import Shop from './components/Shop';
import Home from './components/Home';
import Error from './components/Error';
import {BrowserRouter as Router, Switch,Route} from'react-router-dom';

function App() {  
  return (    
    <Router>
    <div className="App">
      <Nav/>
      <Switch>
      <Route path = '/' exact component = {Home}/>
      <Route path = '/about' component = {About}/>
      <Route path = '/shop'exact component = {Shop}/>
      <Route><Error/> </Route>
      </Switch>          
    </div>
   </Router>
  );
}
export default App;
Copy the code

When routing with Hookrouter requires special rendering because the route is defined in an object, the useRoutes() hook performs the function of the

component by default.

For example, to render a 404 page using Hookrouter routing, we simply pass the error we want to display or the component that contains the error message to render, as shown below (line 17).

import {useRoutes} from 'hookrouter'
import Nav from './components/Nav';
import About from './components/About';
import Shop from './components/Shop';
import Home from './components/Home';

function App() {
  const routes = {
    '/' :() = ><Home/>.'/about' :() = > <About/>.'/shop' :() = > <Shop/>};const routeResults = useRoutes(routes);
  return (
    <div className="App">
        <Nav/>
        {routeResults||<h1>PAGE  NOT FOUND</h1>}
    </div>
  );
}

export default App;
Copy the code

Note: ONE important fact I’ve found is that in Reactrouter

, if routing navigation is not explicitly indicated, it can lead to routing errors in some cases.

For example, if the path to {Home} is not explicitly specified, the application will not navigate to any other path starting with a /. Therefore, the application does not route to {About} or {Shop} components, but all the way to the home page. However, in Hookrouter, because the route is declared as an object, there is no need to explicitly declare the navigation path.

3. Use Hookrouter to navigate

Use through Reactrouter to navigate through the application. In addition, in the React application, you can use it to customize and interactively manage navigation.

import React from 'react'
import {Link} from 'react-router-dom'

function Nav() {
    return (
        <div>
            <nav>
                   <ul className='nav-links'>                      
                      <Link className='Link' to='/'>
                        <li>HOME</li>
                      </Link>
                      <Link className='Link' to='/about'>
                        <li>ABOUT</li>
                      </Link>
                      <Link className='Link' to='/shop'>
                        <li>SHOP</li>
                      </Link>
                  </ul>                
            </nav>
        </div>)}export default Nav
Copy the code

Hookrouter uses A component to provide the functionality of A component. is A wrapper for the tag from HTML, fully compatible with the functionality of the anchor tag.

The main difference between and is that pushes the URL to the history stack instead of loading A new page. Therefore, the onclick function must be wrapped by A component to intercept the click event, stop the default behavior, and push the URL onto the history stack.

import React from 'react'
import {A} from 'hookrouter'

function Nav() {
        return (
            <div>
                <nav>
                        <ul className='nav-links'>
                          
                          <A className='Link' href='/'>
                            <li>HOME</li>
                          </A>
                          <A className='Link' href='/about'>
                            <li>ABOUT</li>
                          </A>
                          <A className='Link' href='/shop'>
                            <li>SHOP</li>
                          </A>
    
                        </ul>
                </nav>
            </div>)}export default Nav
Copy the code

4. Process dynamic routes

Some components contain dynamic parts that must be rendered according to the REQUIREMENTS of the URL. URL parameters are used to set dynamic values in the URL. In Reactrouter, placeholders are passed to the path item starting with a colon in the
component.

To prove this judgment, let’s consider displaying a list of products on the application’s store page. When a user clicks on a particular product, they should be directed to the details page for that product. Navigation is dynamic, passing the product ID as a placeholder in the path item.

 <Route path = '/shop/:id' component = {Details}/>
Copy the code

In Hookrouter, URL parameters are passed in the same way as in Reactrouter, and the structure is the same.

const routes = {
     '/shop/:id':({id}) = ><Details id={id}/>
  };
Copy the code

However, Hookrouter handles URL parameters differently.

  1. It reads URL parameters using keys defined in the route object.
  2. Put them into an object, and the named parameters are forwarded to the routing result function as a composite object.
  3. Dynamic properties are extracted using object deconstruction, which can then be applied to related components.

Therefore, as you can see, the results obtained with Reactrouter can also be achieved with Hookrouter.

5. Other features of Hookrouter

Programmed navigation

Navigate (URL, [replace], [queryParams]) functions of the Hookrouter dependent package can be used to send the user to a specific page defined by an absolute or relative URL provided. For example, to navigate to the about page, use the following code snippet.

Navigate ('/about)Copy the code

Navigate () is a forward navigation by default. Therefore, a new entry is created in the browsing history, and the user can click the back button in the browser to return to the previous page.

redirect

Hookrouter uses useRedirect() hook to handle redirects. It takes a source route and a destination route as parameters.

useRedirect('/'.'/greeting');
Copy the code

Whenever the/path is matched, useRedirect() automatically redirects the user to the /greeting path.

This hook triggers an alternate route navigation. Therefore, in the navigation history, there will be only one entry. Therefore, if a redirection occurs from/to /greeting, as shown in the last code snippet, the/route will not appear in the browsing history.

Many other functions of the Reactrouter library (in addition to those discussed here) can be implemented using the Hookrouter module, such as nested routing, lazy loading components, and server-side rendering.

Also, feel free to check the Hookrouter documentation for more information about this module.

Deficiency in

I’ve noticed that sometimes Hookrouter doesn’t work in create-React-app, which has strict mode enabled by default in the latest version.

However, you can use Hookrouter simply by removing the

component from index.js.

<React.StrictMode>
  <App />
</React.StrictMode>
Copy the code

Another disadvantage is that this module is relatively new. It may contain unknown and unusual errors that lead to unexpected results.

This paper summarizes

As you can see from the examples above, the Hookrouter module provides a cleaner, faster, and more flexible option for handling routes in React applications.

It provides most of the functionality of the Reactrouter library. So I encourage you to try it out and use it in small projects first.

Thanks for reading!

If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.