DEV Community

Cover image for A/B Testing through React federated modules
Ibrahim Shamma
Ibrahim Shamma

Posted on

A/B Testing through React federated modules

There are a lot of areas to start on your journey towards implementing Module Federation.

One of them is A/B Testing.

What is A/B Testing?

A/B testing is a user experience research methodology.
A/B tests consist of a randomized experiment that usually involves two variants, although the concept can be also extended to multiple variants of the same variable.

Still Curious what is module federation? Check me out!

Repo

To check out the github repo click here

Architecture

apps
├── app1
├── app2
├── host
Enter fullscreen mode Exit fullscreen mode
  • app1,app2 are the federated different variants
  • host is our main site where our a/b tests will happen

In case you are wondering how to setup the environment, you better check out part 1 of this series here

Now the fun part, code

We go to the host, and create src/variant.tsx with the following code:

import React from "react";

const variants = [
  React.lazy(() => import("app1/App")),
  React.lazy(() => import("app2/App")),
];

const Variant = ({ text }: { text: string }) => {
  const Component = variants[Math.floor(Math.random() * variants.length)];

  return <Component text={text} />;
};

export default Variant;
Enter fullscreen mode Exit fullscreen mode

NOTE: Don't forget to add type definition for the two lazy loaded modules, simply inside the host/src/react-app-env.d.ts

declare module "app1/App";
declare module "app2/App";
Enter fullscreen mode Exit fullscreen mode

Now, the code above it is all about dynamically import the federated modules from the different apps. And then choose one of them to show up here.

Note that both components needs to have the same props since both will be interacted with from the same interface.

Now you only need to import this variant.tsx into your app normally:

import Variant from "./variant";

function App() {
  return (
    <>
      <Variant text="+ loaded from Host" />
    </>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Always Try to isolate your main app components from the underlying importing logic that consists of dynamic, lazy loading, and suspension which we will go through later in this series.

Your Homework

If you noticed, we are importing two JS bundles and only using one, if we had for example 5 A/B tests we would be importing 4 bundles that will not be using, how can you optimize this?

Top comments (1)

Collapse
 
opensourcee profile image
OpenSource

Good work, mate. I can see us using it for WebCrumbs (here, if you want to join).