The Magic of React Router

Praveen RajPraveen Raj
2 min read

Back in the day, navigating between pages in a web app was straightforward—you'd use the <a> tag to link to different pages. This worked fine, but every time you clicked a link, the entire page would reload, slowing things down. Then React came along, offering a way to build web apps with reusable components, making development more efficient. But the real magic behind React lies in how it handles navigation with something called React Router.

The creators of React understood that sticking with the traditional <a> tag would undermine the whole point of React’s smooth, component-based structure. To solve this, they introduced React Router—a tool that allows us to switch between different components of a page without reloading the entire app. Instead of using <a>, you use Link and NavLink, which look similar but perform so much better. They allow you to load only the parts of the page that need to change, keeping everything else intact, which makes your app feel faster and more seamless.

To use React Router, you first define your routes in your main file, often called index.js or App.js. These routes tell your app which component to display when a user navigates to a specific path. Then, in the components where you want to create links, you use Link or NavLink. The difference between these two is small but handy—NavLink adds an active state to the link, which can be useful for styling.

Now, you might wonder, "Why go through all this trouble? Why not just render components directly where needed?" The answer lies in the power of nested routing and layout components. React Router lets you create a consistent layout for your app and then render only the necessary parts of it, rather than reloading the entire page. This way, your app stays efficient and provides a smoother user experience.

Another cool feature of React Router is redirection using the useNavigate hook. It's a concept worth exploring, and we might dive into it another time.

For a deep dive into React Router, you can check out the official documentation : https://lnkd.in/ecR5KMxx.

0
Subscribe to my newsletter

Read articles from Praveen Raj directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Praveen Raj
Praveen Raj

I'm Praveen Raj Purak, a passionate developer with strong expertise in backend technologies like Node.js, MongoDB, and SQL, alongside skills in React and React Native. I focus on building full stack projects and continuously enhancing my backend proficiency. On Hashnode, I share insights from my learning journey and past experiences to support the tech community.