CPT Custom Hooks, React Router
When I personally self-taught of react, I have never learned about react hooks. I have watched older version of react and tried to understand what class components are and how ‘this’ is working. And of course, ‘this’, gives me lot of confusion.
Ever since I have been studying ‘React hooks’ in bootcamp, react opens up for me to a totally different world called, ‘Single Page Application’. I have learned about building components, changing state, passing props, and even interacting with APIs. There is one last major feature to talk about when it comes to making single-page applications: how can I separate out our components onto separate “pages”, each with their own unique URL? This is where client-side routing comes in.
Client-side routing brings with it some great benefits. The major one is speed. Since we are only making one request to the server, we don’t have to wait for a round trip server call for each page change. We have everything stored on the client-side already, so we just notify our client-side code to display the info as we need it.
The most popular client-side routing library to use with React is React Router. React Router ships with a few hooks that let you access the state of the router and perform navigation from inside your components.We will take a look closer of what useful React router custom hooks are.
{ useHistory }
The useHistory hook gives you access to the history instance that you may use to navigate.
{ useParams }
useParams returns an object of key/value pairs of URL parameters. Use it to access ‘match.params’ of the current <Route />.
{ useRouteMatch }
The useRouteMatch hook attempts to match the current URL in the same way that a <Route /> would. It’s mostly useful for getting access to the match data without actually rendering a <Route />.
so, instead of using <Route />, we can just use this { useRouteMatch } hook to access to another component easier. { useRouteMatch } either takes no argument and returns the match object of the current <Routes />, or takes a single argument, which is identical to props argument of matchPath. It can be either a pathname as a string (like the example above) or an object with the matching props that Routes accepts.
{ useLocation }
The useLocation hook returns the location object that represents the current URL. You can think about it like a useState that returns a new location whenever the URL changes.
This could be really useful in a situation where you would like to trigger a new “page view” event using your web analytics tool whenever a new page loads.
Conclusion
In the early days of the internet, we would have had to create separate HTML pages for lots of page application. Now, with React, and this react custom hooks for DOM, we can write abstract components that fill in the data for each ‘page’ on demand.
Reference: https://reactrouter.com/web/api/