Redirect and Redux Is Rendering My Page Again
Editor's annotation: This React Hooks and React Router tutorial was last updated on x February 2022 to update outdated information and include new data about React Router.
Since the appearance of React Hooks, a lot of things have changed. Some things nosotros didn't have issues with before take started causing concern. The features and possibilities that come with Hooks accept redefined how we approach certain concepts in React, and routing happens to be i of them.
Before we proceed, I would like to mention that this post is not intended in any way to accept shots at React Router or scoff its importance. Instead, we are going to explore other possibilities and look at how nosotros can improve the routing experience in React apps using Hooks.
To this event, nosotros'll be making references to the React Router and besides to hooksrouter for demonstration purposes. Kickoff, let's take a closer look at React Router.
What is React Router?
React Router is a pop declarative way of managing routes in React applications. Information technology takes abroad all of the stress that comes with manually setting routes for all of the pages and screens in your React application. React Router exports 3 major components that help us make routing possible — Route, Link, and BrowserRouter.
Is React Router necessary?
React router tin exist an overkill for certain projects where all you lot demand is bones navigation and routing functionalities. In that context, React Router is not necessary at all. That said, React Router is rich with navigational components that etch declaratively with your application, which tin can be very useful for larger and more complex navigational requirements in React applications. It is also smashing for React Native applications.
Is React Router built into React?
No, React Router is not built into React. It's a divide routing library built on top of React specifically for providing routing and navigation functionalities in React applications. When adding React Router to your React applications, you import it from it's own module, like this:
import { Router , Route , Switch } from "react-router" ;
Still, you should not install it directly into your project similar that. If you're writing an application that will run in the browser, you should instead install R eact Router DOM.
Practice I demand React Router and React Router DOM?
You don't need R eact Router and React Router DOM together. R eact Router DOM gives you access to React Router past default. If you detect yourself using both, it'southward OK to get rid of React Router since you already take it installed as a dependency within React Router DOM. Note, withal, that React Router DOM is only available on the browser, so y'all can only use information technology for spider web applications
Routing in React Router
If you were edifice a React app and you had three pages, here'due south how you would conventionally implement routing with React Router:
import Users from "./components/Users"; import Contact from "./components/Contact"; import About from "./components/About"; role App() { return ( <div> <Router> <div> <Route path="/near" component={Nearly} /> <Route path="/users" component={Users} /> <Road path="/contact" component={Contact} /> </div> </Router> </div> ); } The <Road/> component imported from the React Router package takes in 2 props, the path to direct the user to the specified path and the component to define the content in the said path.
The Hooks alternative to routing
All thanks to Chris Engel for the hookrouter tool that we will be focusing on to drive home these demonstrations. The hookrouter module exports a useRoutes() hook that evaluates a predefined routes object and returns a effect. In the routes object, y'all define your routes as keys with their values equally functions that will be called when the routes lucifer. Here's a applied demonstration:
import React from "react"; import Users from "./components/Users"; import Contact from "./components/Contact"; import Virtually from "./components/Near"; const routes = { "/": () => <Users />, "/about": () => <Most />, "/contact": () => <Contact /> }; export default routes; Personally, I like this method. Why? Well, because nosotros didn't accept to practice and then much work. With React Router we had to render the <Route/> component for all the individual routes in our app. Non to mention all of the props we passed to it. Dorsum to hooks, we tin can use this defined Routes in our app by simply passing it to the useRoutes() Hook:
import {useRoutes} from 'hookrouter'; import Routes from './router' part App() { const routeResult = useRoutes(Routes) return routeResult } And this gives us exactly the aforementioned result we'd get with the React Router routing demonstration only with a cleaner and lighter implementation.
Check out this editable code case on CodeSandbox.
React Router navigation
React Router also gives usa admission to the <Link/> component. It helps u.s.a. customize route navigations and manage interactive routing in React apps. We accept a react app with three routes, let's return the 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 About from "./components/About"; office App() { return ( <div className="App"> <Router> <div> <ul> <li> <Link to="/most">Virtually</Link> </li> <li> <Link to="/users">Users</Link> </li> <li> <Link to="/contact">Contact</Link> </li> </ul> <Route path="/virtually" component={Near} /> <Route path="/users" component={Users} /> <Route path="/contact" component={Contact} /> </div> </Router> </div> ); } This creates the navigations nosotros need to go from one folio to some other within the app. Hither's a visual representation of what we are doing here.
Here's an editable lawmaking case.
The Hooks alternative to React navigation
The hookrouter module provides a wrapper effectually the HTML anchor tag <a/> as <A/>. It is attainable every bit a React component and 100% feature uniform to the native <a/> tag. The only difference is that it pushes navigations to the history stack instead of actually loading a new page.
const routes = { "/user": () => <Users />, "/nigh": () => <About />, "/contact": () => <Contact /> }; function App() { const routeResult = useRoutes(routes); return ( <div className="App"> <A href="/user">Users Page</A> <A href="/about">Almost Page</A> <A href="/contact">Contacts Page</A> {routeResult} </div> ); }
Here'due south an interactive demo.
Programmatic navigation
The hookrouter module gives u.s.a. access to a navigate() Hook function that we can pass a URL to and it will navigate the user to that URL. Every call to the navigate() function is a frontwards navigation, as a result, users can click the browser's back button to return to the previous URL.
navigate('/user/'); This happens by default. Notwithstanding, if y'all need a different beliefs, you tin can practise a replace navigation. How? you might ask, well the navigation() claw primarily takes-in three parameters — navigate(url, [replace], [queryParams]) the 2d parameter is used to issue the supercede behavior. Information technology erases the current history entry and replaces it with a new i. To achieve that effect, but set its argument to true.
navigate('/user', true); React Router switch
Conventionally, React Router uses the <Switch/> component to return a default page when the defined navigation routes are not matched. Usually, it renders a 404 page to let the user know that the selected route is non defined in the application. To practise this, we wrap all the rendered routes within the <Switch/> component and return the 404 page without defining a path prop for information technology:
import { Route, Link, BrowserRouter equally Router, Switch } from "react-router-dom"; import Users from "./components/Users"; import Contact from "./components/Contact"; import Dwelling house from "./components/Most"; import NoPageFound from "./components/NoPageFound.js"; part 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> ); } This way, whenever an undefined path is reached, React Router renders the NopageFound component. It is a very great way of letting users know where they are and what is going on at all times while navigating your React site.
Hither's an editable code instance.
The 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, information technology becomes really straightforward to conditionally return routes. If we define a NoPageFound file to render by default when a selected route is not defined, we'll simply need to pass that file for rendering alongside our result part like so:
import { useRoutes, A } from "hookrouter"; import routes from "./router"; import NoPageFound from "./components/NoPageFound"; office App() { const routeResult = useRoutes(routes); return ( <div className="App"> <A href="/user">Users Folio</A> <br /> <A href="/about">About Page</A> <br /> <A href="/contact">Contacts Folio</A> <br /> {routeResult || <NoPageFound />} </div> ); }
Compared to using the <Switch> component in React Router to render default pages, I think this seems a bit cleaner and more readable.
Check out this example.
React Router redirects
Redirection happens when we desire to dynamically directly a user from one route to some other. For instance, during login, when a user successfully logs in, we would want to redirect them from the ('/login') route to the ('/dashboard') route.
With React Router, nosotros can do this in a few ways — using the history object or the <Redirect/> component. For case, If nosotros have a login course, nosotros can leverage the browser's history object to push the user to the '/dashboard' route when are logged in:
import React from 'react' class Login extends React.Component { loginUser = () => { // if (user is logged in successfully) this.props.history.push('/dashboard') } render() { return ( <grade> <input blazon="proper noun" /> <input type="email" /> <button onClick={this.loginUser}>Login</button> </form> ) } } export default Login Consequently, nosotros tin can too use the <Redirect/> component bachelor in React Router to dynamically redirect users.
The Hooks alternative to redirects
The hookrouter module exports a useRedirect() Hook that can have a source route and a target road equally parameters.
useRedirect('/user', '/dashboard'); This will automatically redirect users to the '/dashboard' road whenever the '/user' path is matched. For case, if we didn't desire to prove any users but instead redirect a user automatically from the to their '/dashboard', we would define our app similar this:
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 } Hither's the visual output of this process:
It is worthy to note that the useRedirect() Hook triggers a replacement navigation intent. As a result, there volition merely be i entry in the navigation history. This ways that if redirection happens from '/user' to '/dashboard' as we showed in the last snippet, the '/user' route will not appear in the browsing history. We will but accept the '/dashboard' route.
Handling URL parameters with React Router
URL parameters assist us render components based on their dynamic URL's. It works in a similar mode with nested routes all the same, in this case, the routes are not exactly irresolute — rather, they're updating.
For instance, if we had different users in our app, it would make sense to place them separately with their individual routes like 'user/user1/' and 'users/user2/' etc. To do that, we'll need to use URL parameters. In React Router, we simply pass a placeholder (similar id) starting with a colon to the path prop in the <Road/> component:
<Route path="users/:id" component={Users} /> Now, if you navigate to 'users/i' on the browser, this particular user will exist available in your Users.js prop.
The Hooks culling to handling URL parameters
There's non much difference in the way the hookrouter treats URL parameters as compared to React Router. The construct is the same (i.due east you lot tin can pass your URL parameters to your target routes using a colon and the parameter name).
Withal, there'south still a divergence in the fashion the road Hook works. Information technology reads all URL parameters and puts them into an object. It does this using the keys you divers in the routes object. Then all the named parameters volition be forwarded to your route result function as a combined object.
const routes = { '/user/:id': ({id}) => <User userId={id} /> } Using object destructuring, we simply take the id property from the props object so use it onto our component. That way, we attain exactly the aforementioned result as we did with the React Router alternative.
Conclusion
Like I said at the beginning of this post, the intention is to offer you an culling way of routing in your React projects. React Router is a great tool however, I recollect with the arrival of Hooks, a lot of things have changed in React and that besides includes how routing works. This module based on Hooks offers a more than flexible and cleaner mode if handling routes in smaller projects. If you like trying out new tools as much as I do, I encourage you to requite information technology a shot.
In that location are so many other aspects we haven't covered nonetheless in this post, like how both tools handle nested routing, etc. Feel free to learn more most the hookrouter module here.
Full visibility into production React apps
Debugging React applications can be difficult, particularly when users experience issues that are difficult to reproduce. If y'all're interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking wearisome network requests and component load time, try LogRocket.
LogRocket is like a DVR for web and mobile apps, recording literally everything that happens on your React app. Instead of guessing why problems happen, yous tin aggregate and study on what country your application was in when an issue occurred. LogRocket besides monitors your app's functioning, reporting with metrics like client CPU load, customer memory usage, and more.
The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.
Modernize how you debug your React apps — start monitoring for free.
Source: https://blog.logrocket.com/how-react-hooks-can-replace-react-router/
0 Response to "Redirect and Redux Is Rendering My Page Again"
Post a Comment