THE 4 HOOKS OF REACT ROUTER
Its one of the popular website routing system.
We have 4 types of react hooks available:
- useHistory 2. useLocation 3. useParams 4. useRouteMatch
useParams:
Used for getting the router parameter from the URL parameters.
function App() {
return (
<Router className=”App”>
<Switch>
<Route path=”/home”><Home /></Route>
<Route path=”/country/:countryName”>
<CountryDetail />
</Route>
<Route exact path=”/”><Home /></Route>
<Route path=”*”><NoMatch /></Route>
</Switch>
</Router>
);
}
- In the bold area of above code, we can see we have added a specific path /country following a dynamic path /:countryName. /country path remains constant and /:countryName doesn’t.
Next..
const CountryDetail = () => {
const { countryName } = useParams();
const [country, setCountry] = useState({});
// console.log(country);
useEffect(() => {
fetch(`https://restcountries.eu/rest/v2/name/${countryName}`)
- After providing dynamic path in CountryDetail component, we can access and use that dynamic value (countryName) setting as a value of useParams hooks and used in our useEffect method to fetch data from API.
useLocation:
It’s like a useState that returns a new location every time the URL changes. Used to get the global location in our component.
const country = () => {
const location = useLocation();
return
<p>{JSON.stringify(location )}</p>;
In the code above, we used the useLocation hook in country to get the location object and assigned it to location and gets it stringify using JSON
useHistory:
Used for going to some history or object we want to navigate. It let us go back and push to that specific path.
const history = useHistory();
const handleClick = (name) => {
history.push(`country/${name}`)
}
In this example we set useHistory hooks with a const named history. We used a click handler with parameter (name). Then we a set a path where we want to navigate with a dynamic path {name} that we used as parameter.
useRouterMatch:
It matches the current URL how <Route> works. Useful for getting data without rendering like <Route>.
Source: Reactrouter.com
Now, instead of:
function BlogPost() {
return (
<Route
path=”/blog/:slug”
render={({ match }) => {
// Do whatever you want with the match…
return <div />;
}}
/>
);
}
you can just:
function BlogPost() {
let match = useRouteMatch(“/blog/:slug”);
}
Conclusion:
All knowledge and info are shared as a newbie learner of react. Please make correction if anything is wrong.
Thank you..