Q1Beginner
How does React Router v6 work and what are the key hooks?
💡 Hint: Nested Routes with Outlet, useNavigate instead of useHistory, useParams, useSearchParams
import { BrowserRouter, Routes, Route, Outlet } from 'react-router-dom';
// Route definition — v6 syntax
function App() {
return (
}>
} />
} />
} />
} />
);
}
// Layout component — Outlet renders matched child route
function Layout() {
return (
);
}
Key hooks:
// Navigate programmatically
const navigate = useNavigate();
navigate('/users/123');
navigate(-1); // go back
// Route params — /users/:id
const { id } = useParams();
// Query string — /users?tab=active
const [searchParams, setSearchParams] = useSearchParams();
const tab = searchParams.get('tab');
// Current location
const location = useLocation();
console.log(location.pathname, location.search, location.state);
💡 v6 removed useHistory (now useNavigate), Switch (now Routes), exact prop (now default), and Redirect (now Navigate component). Nested routes no longer need full paths — relative routing is the default.