logoalt Hacker News

pscanftoday at 4:00 PM3 repliesview on HN

I've done something similar in a React project I'm working on to avoid dealing with the insanity that is react-router.

Call me naïve, but routing in a single page application is just not that hard of a problem. At the core it's about having a piece of state¹ (your active route) which determines which part of the app you want to render–something you can do with a switch statement². On top of that, you want to synchronize that state to the page URL³.

Doing it yourself requires more boilerplate code, no question about it. But it's not that much code tbh (not very complex either), and you get back control over that important piece of state, which otherwise remains opaque and difficult to work with–i.e., its "shape" is pre-determined by the routing library you use. For example, react-router doesn't support parallel routes.

¹ https://github.com/superegodev/superego/blob/main/packages/a...

² https://github.com/superegodev/superego/blob/main/packages/a...

³ https://github.com/superegodev/superego/blob/main/packages/a...


Replies

embedding-shapetoday at 4:37 PM

I also basically re-invent a tiny 50 line router for every web project. Hardly ever go beyond "Map URL -> Page" and "Map URL + Parameters -> Page with properties", and when you do, knowing 100% how it works helps a lot.

I also agree it isn't a hard problem, but personally I'd say you got the flow the wrong way around. You don't want to "synchronize state to the page URL" but rather treat the page URL as something you create state from, so it works both when you navigate there by pressing anchor tags, or the user manually enters the URL, and it gets a bit easier to manage.

Basically, URL is the top-level state, and from there you derive what page, then render that page, rather than the other way around.

show 1 reply
simon04today at 4:54 PM

A very tiny router is provided by nanostores: https://github.com/nanostores/router

sampullmantoday at 4:36 PM

I don't think it's naive, I often do the same in Vue. A pretty useful subset of vue-router can be implemented in less than a tenth of the bundle size.