<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Visalan H on Medium]]></title>
        <description><![CDATA[Stories by Visalan H on Medium]]></description>
        <link>https://medium.com/@visalan?source=rss-9e5fd6a25819------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*wlX70sfv5GsNs56C</url>
            <title>Stories by Visalan H on Medium</title>
            <link>https://medium.com/@visalan?source=rss-9e5fd6a25819------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 00:51:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@visalan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How I Built a Lightweight React Router Using Context and Browser APIs]]></title>
            <link>https://medium.com/@visalan/how-i-built-a-lightweight-react-router-using-context-and-browser-apis-7813af1cd84c?source=rss-9e5fd6a25819------2</link>
            <guid isPermaLink="false">https://medium.com/p/7813af1cd84c</guid>
            <category><![CDATA[react-context]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[browser-api]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-router]]></category>
            <dc:creator><![CDATA[Visalan H]]></dc:creator>
            <pubDate>Fri, 29 Aug 2025 10:55:08 GMT</pubDate>
            <atom:updated>2025-08-29T10:55:08.135Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Most developers never question how React Router actually works under the hood. They just install it and move on. But what if I told you that the entire routing mechanism can be built in about 100 lines of code using just React’s <a href="https://react.dev/learn/passing-data-deeply-with-context">Context API</a> and a single <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/popstate_event">browser event</a>?</p><p>That’s exactly what I discovered when I built <a href="https://github.com/Visalan-H/vizz-router">vizz-router</a>, my own lightweight React router implementation. In this post, I’ll walk you through the core concepts that make client-side routing possible. React Context for state management and the popstate event for browser history integration. By the end, you’ll understand not just how routing libraries work, but how to build one yourself.</p><h3>The Power of React Context in Routing</h3><h4>What Makes Context Perfect for Routing</h4><p>React Context is often overlooked, but it’s absolutely perfect for routing applications. Here’s the thing, routing state needs to be everywhere in your app. Your header components need it. Your sidebar needs it. Your main content needs it. But passing this data down through dozens of components? That’s an actual nightmare.</p><p>Think about it, your navigation links in the header need to know the current route, your sidebar needs to highlight the active page, and your main content area needs to render the right component. Context provides this <strong><em>global state management</em></strong> seamlessly.</p><h4><strong>So how do you actually build this Context?</strong></h4><p>It’s simpler than you think. In vizz-router, I created a basic React Context with just two pieces of information:</p><pre>const RouterContext = createContext({<br>  location: &quot;&quot;,<br>  navigate: () =&gt; {},<br>});</pre><p>That’s it. The current <strong><em>location</em></strong> tells components which page they’re on, and the <strong><em>navigate</em></strong> function lets them change routes programmatically.</p><h3>Handling Browser History with Popstate</h3><h4>The Popstate Event: Your Router’s Best Friend</h4><p>Here’s where things get interesting. The <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/popstate_event">popstate</a> event is the <strong><em>secret sauce</em></strong> that makes client-side routing feel native. This event fires whenever the user clicks the browser’s back or forward buttons, and it’s what allows your router to stay in sync with browser history.</p><p>No popstate handling means your router can’t detect browser navigation. URL changes, your state doesn’t, content stays the same.</p><h4>Creating Your Popstate Listener</h4><p>In vizz-router, the popstate handling happens inside the main Router component:</p><pre>useEffect(() =&gt; {<br>  const handlePopState = () =&gt; {<br>    setLocation(window.location.pathname);<br>  };<br><br>  window.addEventListener(&#39;popstate&#39;, handlePopState);<br>  <br>  return () =&gt; {<br>    window.removeEventListener(&#39;popstate&#39;, handlePopState);<br>  };<br>}, []);</pre><p>This setup makes sure the router’s state always matches the current URL when users click the back button.</p><p>The context then propagates this change to all consuming components, triggering the appropriate re-renders.</p><p>The cleanup function just removes the event listener when the router unmounts.</p><h3>Building the Navigation System</h3><h4>Navigating Programmatically Without Page Reloads</h4><p>Traditional anchor tags cause full page refreshes, which defeats the purpose of single-page applications. Instead, we use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/History_API">History API’s pushState</a> method to update the URL without triggering a page reload.</p><p>The navigate function combines pushState with context updates:</p><pre>const navigate = (path) =&gt; {<br>  window.history.pushState({}, &#39;&#39;, path);<br>  setLocation(path);<br>};</pre><h4>The Link Component: Anchor Tags Without Reloads</h4><p>The Link component in vizz-router acts like a custom anchor tag that prevents the normal browser page reload when clicked. Here’s how it’s implemented:</p><pre>function Link({ to, children, ...props }) {<br>  const { navigate } = useContext(RouterContext);<br><br>  const handleClick = (e) =&gt; {<br>    e.preventDefault();<br>    navigate(to);<br>  };<br><br>  return (<br>    &lt;a href={to} onClick={handleClick} {...props}&gt;<br>      {children}<br>    &lt;/a&gt;<br>  );<br>}</pre><p>This component does three important things:</p><ol><li><strong>Prevents Default Behavior</strong>: The e.preventDefault() stops the browser from doing a full page reload when users click the link.</li><li><strong>Uses Router Context</strong>: It pulls the navigate function from the RouterContext, connecting it to the router&#39;s internal navigation system.</li><li><strong>Maintains Familiar HTML</strong>: It still renders an actual &lt;a&gt; tag with proper href attributes, so your links work with right-clicks, <strong>accessibility</strong> tools, and <strong>SEO</strong> crawlers.</li></ol><h3>Route Matching and Component Rendering</h3><h4>How Routes Use Context to Render</h4><p>The Routes component looks at the current URL from context and decides which Route to display. This keeps navigation state separate from what gets rendered on screen.</p><p>Each Route checks if its path matches the URL, match means show content, no match means show nothing. This pattern scales well as your app grows and makes adding new routes straightforward.</p><p>We wrap all our individual &lt;Route /&gt;components inside the &lt;Routes /&gt; component while using it.</p><h4>The Hook System</h4><p>Custom hooks such as useNavigate and useRouter simplify access to the router context. This means components don’t have to work with context directly, making your code cleaner and easier to manage.</p><pre>export const useRouter = () =&gt; {<br>    const context = useContext(RouterContext);<br>    if(!context) throw new Error(&#39;useRouter must be used within a Router&#39;);<br>    return context;<br>};<br><br>export const useNavigate = () =&gt; {<br>    const { navigate } = useRouter();<br>    return navigate;<br>};</pre><h3>Conclusion</h3><p>Building vizz-router taught me that React Context isn’t just useful for theming or user authentication. It’s the perfect solution for any global state that needs to be accessible throughout your component tree. Combined with the popstate event and History API, you can create a fully functional router in about 100 lines of code.</p><p>The key insights are simple:</p><ul><li>Use Context for state management → Share routing state across components</li><li>Listen to popstate for browser integration → Detect back/forward button clicks</li><li>Leverage pushState for navigation → Update URLs without page refreshes</li></ul><p>The next time you import React Router, you’ll know exactly what’s happening under the hood. That’s the difference between using a tool and truly understanding it.</p><p>Thanks for taking the time to read this! Now go build something awesome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7813af1cd84c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>