HomeToolsAbout

History

What is it

React Router allows client side routing in React SPA.

  • React Router allows current HTML page to dynamically route to a new content without fully reloading the HTML.
    • Obviously, through Javascript (since JS was created to programmatically/dynamically edit HTML in the first place).

When the URL changes, React Router intercepts the request and determines which component(s) should be rendered based on the defined routes.

  • preventing the browser from performing a default link navigation

React Router uses the History API to manipulate the browser's history stack.

  • React Router's history API uses Remix's history lib underneath.

React Router checks the updated URL against the defined routes and once a matching route is found, React Router dynamically renders the corresponding component.

The history library lets you easily manage session history anywhere JavaScript runs. A history object abstracts away the differences in various environments and provides a minimal API that lets you manage the history stack, navigate, and persist state between sessions.

useHistory

The useHistory hook gives you access to the history instance that you may use to navigate.

import { useHistory } from "react-router-dom"; function HomeButton() { const history = useHistory(); function handleClick() { history.push("/home"); } return ( <button type="button" onClick={handleClick}> Go home </button> ); }

Typing Router history object

import { RouteComponentProps } from 'react-router-dom'; type RouteHistory = RouteComponentProps['history']; const history: RouteHistory = useHistory();
AboutContact