Routing in React with hooks

Routing in React with hooks
Average rating: 1.8
(5 votes)

Thanks! You’ve rated this material!

Do you like experiments as we do? We are inviting you to the world of React experiments. How about routing in React with hooks? Are you with us? If so, check this material. 

The router module is published on npm and can be installed by calling npm -i hookrouter. It has zero dependencies and adds about 2.9kb to your bundle.

This is what you have to keep in mind:

  • You can define your possible routes as an object with urls as keys and result functions as values. The useRoutes() hook consumes the routes object, evaluates them one by one and checks if they match the current url path. If one of the routes matches, its function will be called.
  • You can also use multiple URL parameters if you want to – just give them different names.
  • If you call the next useRoutes() inside a child component, it will not match against the full url path but only against the part that remains, which would be /details. You can nest routes as much as you like.
  • We perform the redirect before we match any routes to prevent an unnecessary re-render of the <ProductArea /> component. With this approach, other components may just navigate the user to the product area and leave the decision where the user should end up to that component.

Feel free to check the examples here.

You can rely on us and read our article where you can meet React 360 (or React VR). Enjoy!

Rate this article, if you like it

Thanks! You’ve rated this material!

Got a project? Let's discuss it!

Mailing & Legal Address

Syndicode Inc. 340 S Lemon Ave #3299, Walnut CA, 91789, USA

Visiting & Headquarters address
Kyiv Sofiivska 1/2a, 01001, Kyiv, Ukraine
Dnipro Hlinky 2, of. 1003, 49000, Dnipro, Ukraine
Email info@syndicode.com
Phone (+1) 9035021111