It's possible to utilize hooks on the server-side as well.
Hooks are essentially normal functions. However, if you try to access something specific to the browser such as window
, localStorage
, etc., the server will recognize that it's a task meant for the client only.
// src/hooks/useOnServer.ts
import { useIsSSR } from "@react-aria/ssr";
/**
* The useIsSSR hook indicates whether the code is running on the server-side or in the browser.
*/
export default function useOnServer() {
const isServer = useIsSSR();
console.log(isServer ? "Server" : "Client");
}
Here's how you can implement it:
// src/pages/home.tsx
import useOnServer from "src/hooks/useOnServer";
export default function Home() {
// Activate the hook!
useOnServer();
return <p>Success!</p>
}
This approach offers the flexibility of isomorphic programming. For example,
- You could create a validation system to ensure form validation is implemented only once. This avoids the common issue where backend and frontend developers need to sync up each time modifications are made to a form. With this method, everything is consolidated into one place.
Think of it like a ticking time bomb 💣 MeteorJS may have been among the first frameworks to introduce isomorphic capabilities (at least from my experience years ago).
This technique may require some brainpower 🧠 and has a learning curve, but the advantages outweigh the challenges. Enjoy exploring isomorphic hooks and consider sharing your open-source creations with the community! 🍀