When an action for navigating to a route is triggered, an action triggers a new state where the router.location.pathname
changes according to the browser's history
.
Another property changes as well: router.location.key
, to a new random string.
Even when the pathname itself doesn't change (clicking on a link to a page from the page itself), the key
still updates.
What's the purpose of the key
property? In which situations would I want my own state to have a randomly generated key
which updates on very action dispatch? Why is it not a number which simply increments?
To detect route change with React Router, we can use the useLocation hook. import { useEffect } from "react"; import { useLocation } from "react-router-dom"; const SomeComponent = () => { const location = useLocation(); useEffect(() => { console. log("Location changed"); }, [location]); //... };
The switch component looks through all of its child routes and it displays the first one whose path matches the current URL. This component is what we want to use in most cases for most applications, because we have multiple routes and multiple plate pages in our app but we only want to show one page at a time.
When we say dynamic routing, we mean routing that takes place as your app is rendering, not in a configuration or convention outside of a running app. That means almost everything is a component in React Router.
Key location means the location where the poker run concludes and the prize or prizes are awarded.
connected-react-router
simply stores the location object from react-router
which in turn creates the location object using the history package. In the readme of history
the key
property is described:
Locations may also have the following properties:
location.key - A unique string representing this location (supported in createBrowserHistory and createMemoryHistory)
It is used internally (e.g. in https://github.com/ReactTraining/history/blob/master/modules/createBrowserHistory.js to find locations in the current history stack) and should be treated as an implementation detail of react-router
. I suspect a random key instead of a incrementing sequence number was simply the easiest way to implement unique ids (you don't have to store the current sequence number).
This causes unnecessary rerender of the current route, when visited once again, because props change. One way to fix that would be to use React.memo
, and comparing the location.path
which stays the same. But then you will have to be careful if your component receives other props, so to include them in the comparison.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With