DEV Community

Garrick Crouch
Garrick Crouch

Posted on


Create a Custom React.js Hook to Get Subdomains

Often times it's extremely useful to be able to easily parse the hostname or domain parts of your website. The use cases are many but we'll just look at how to make a react hook to help us get subdomain info for use in our application.

We'll use the Web API window.location.hostname. It'll return the string representation of the current host.

import * as React from 'react';

export default function useSubdomain(position = 0) {

  const [subdomain] = React.useState(() => {
    try {
      return window?.
    } catch (err) {

  return subdomain;
Enter fullscreen mode Exit fullscreen mode

You can see we just create an array from the hostname parts based on the . as a delimiter, and access the array index you pass in as the argument for the call to the hook.

We could take it a step further and create a function to run this logic at any time, but for now let's just assume that we only want this to run once as we call it, so we would use it like this:

export default function MyComponent() {

  const subdomain = useSubdomain(0);

  return (
      The website subdomain is {subdomain}
Enter fullscreen mode Exit fullscreen mode

You could add checks in to make sure you're actually on a subdomain as well, and also guards for www.

Latest comments (0)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!