DEV Community

Cover image for I used react-router but not for routing
Hồng Phát
Hồng Phát

Posted on

I used react-router but not for routing

I was working on my React project, fetching some data using fetch, and looking for a good way to do something like this Python code:

"{a} {b}!".format(a = "Hello", b = "World") # == "Hello World!"
Enter fullscreen mode Exit fullscreen mode

💡 Why not use JavaScript string interpolation, you may ask? I want to put the params elsewhere, not within the string.

So I spent hours doing Regex went code scavenging on Stack Overflow, and I found this. It’s interesting that there is a function named formatUnicorn right on Stack Overflow’s website, which does exactly what I was looking for:

Stack Overflow's formatUnicorn

But I was hesitant to loot the code. I want to keep my code base as strongly typed as possible, and modifying the String prototype makes me feel insecure. What’s more, I would like to have at least some validation in case someone else forgot to pass in a and/or b. Implementing that seems beyond my scope of work, and installing another library is overkill. I was staring at the import section (just to make sure that I don’t import so much 3rd party stuff to keep our SPA app startup fast since FCP is crucial to our business), and that’s when I saw react-router import…

React Router lets you register routes with params like this:

path: "teams/:teamId",
Enter fullscreen mode Exit fullscreen mode

So they must have implemented that “unicorn format” somewhere. I skimmed over their exports hoping that they would expose that unicorn function so I could use it, and thankfully they did:
import { generatePath } from

And the function is unicornly strong typed:
IDE code completion and type checking for params

💡 Did you expect that TypeScript can infer substrings as types like above? I didn’t!

The moral of the story

Sometimes, installing one more library may not be necessary because what you need is already (unexpectedly) available elsewhere within your project. Bundling too many libraries can greatly affect performance if it is crucial to your business.

I hope my story was inspiring!

Top comments (0)