Programmatic Navigation and useSearchParams
Programmatic Navigation and useSearchParams
1. What is Programmatic Navigation?
Declarative navigation using <Link> and <NavLink> works when a user clicks a visible hyperlink. However, real-world applications frequently require navigation in response to code execution:
- Redirecting a user to their dashboard immediately after a successful login.
- Navigating to an order confirmation screen after completing a checkout payment.
- Redirecting an unauthorized user back to the sign-in page.
In React Router v6+, programmatic navigation is executed using the useNavigate hook.
Delta Navigation (Back & Forward)
useNavigate also allows navigating through browser history:
2. Managing Query Strings with useSearchParams
URL Query Strings (search parameters) are the key-value pairs appended after a ? in the URL:
Query strings are ideal for shareable UI states: filters, search terms, pagination, and sorting.
React Router provides useSearchParams, which functions similarly to React's useState, returning:
- 1
searchParams: A modernURLSearchParamsobject to read current query parameters. - 2
setSearchParams: An updater function to modify URL parameters programmatically.
3. Why Query Params Beat Component State for Search
If an e-commerce catalog stores filters in local useState, when a student finds a great set of courses and copies the URL to send to a friend, the filters are lost because the URL only says /courses.
When filters are stored in searchParams:
- The URL becomes
/courses?category=frontend&sort=rating. - Users can bookmark the page, refresh the browser, or share the link with colleagues, and the exact same filtered state will load immediately!
Practice Quiz
useNavigate?navigate('/dashboard', { replace: true }) and why??category=react&page=1) in React Router?useState?The Prop Drilling Dilemma and Context Solution
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Dynamic URL Parameters with useParams | The Prop Drilling Dilemma and Context Solution |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.