Navigation

A navigation Key is needed to create navigation commands that change the URL. That includes pushUrl, replaceUrl, back, and forward.

Need install react-router-dom & query-string

useRouter

If you use React Router you might have noticed they recently added a number of useful hooks, specifically useParams, useLocation, useHistory, and use useRouteMatch. But let's see if we can make it even simpler by wrapping them up into a single useRouter hook that exposes just the data and methods we need. In this recipe we show how easy it is to compose multiple hooks and combine their returned state into a single object. It makes a lot of sense for libraries like React Router to offer a selection of low-level hooks, as using only the hook you need can minimize unnecessary re-renders. That said, sometimes you want a simpler developer experience and custom hooks make that easy.

Usage

import React from 'react';
import useRouter from '@/hooks/navigation/useRouter';

function MyComponent() {
  // Get the router object
  const router = useRouter();
  // Get value from query string (?postId=123) or route param (/:postId)
  console.log(router.query.postId);
  // Get current pathname
  console.log(router.pathname);
  // Navigate with with router.push()
  return <button onClick={(e) => router.push("/about")}>About</button>;
}

Last updated

Was this helpful?