React Router Crash Course | Chai aur react #12 Summary
In this video, we explored React Router DOM, an essential library for adding navigation to React applications without reloading the page.
Key Takeaways:
React Router Basics:
React Router DOM allows us to handle different routes in a React app efficiently, making navigation seamless without reloading the entire page.
We created a project with multiple components like Home, About, Contact, and GitHub. These components acted as different screens for our app.
Layout Structure:
We set up a Header and Footer to remain static across all pages, while the content in between changes depending on the route.
We used the
Outlet
component from React Router DOM to dynamically load the correct page content between the header and footer.The main layout logic was handled in
layout.js
, which we set up as the primary structure for the app.
Routing Setup:
In the
main.js
file, we defined the different routes using React Router’sRoute
element, specifying which component to load for each route.We learned two ways to set up routes: using an array of route objects or using JSX-based route elements.
Navigation with Links:
Instead of using regular anchor (
<a>
) tags that reload the page, we used React Router’sLink
component to enable navigation without reloading.We also explored
NavLink
, which provides extra functionality like highlighting the active route. This is useful for showing which page is currently active in the navigation bar.
Loader Functionality:
The Loader feature helps pre-fetch data before navigating to a new page, improving user experience by reducing waiting time after clicking.
When a user hovers over a link, the data is fetched in advance, so when they actually click on it, the page loads almost instantly.
Handling Route Params:
- We used
useParams
to extract dynamic parameters from the URL, making it easier to handle routes that rely on data like user IDs or post slugs.
- We used
Optimization Tips:
Always provide a unique key when rendering lists of elements to help React efficiently re-render the correct components.
Using
useLoaderData
allows us to access the data fetched by the loader in a specific route, ensuring the right data is used for each component.
Subscribe to my newsletter
Read articles from Vishesh Gupta directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by