Skip to main content

Using with React

For usage in React, we recommend using the below EppoRandomizationProvider at the root of your component tree. By default, this component waits for initialization of the SDK before rendering its children. If waitForInitialization is set to false, the SDK getStringAssignment function will return null assignments while initializing and will only start assigning subjects when a new browser session is started.

import { useEffect, useState } from "react";

import { init } from "@eppo/js-client-sdk";

interface IEppoRandomizationProvider {
waitForInitialization?: boolean;
children: JSX.Element;
loadingComponent?: JSX.Element;
}

export default function EppoRandomizationProvider({
waitForInitialization = true,
children,
loadingComponent = <div>Loading...</div>,
}: IEppoRandomizationProvider): JSX.Element {
const [isInitialized, setIsInitialized] = useState(false);
useEffect(() => {
init({
apiKey: "<YOUR-SDK-KEY>",
assignmentLogger: {
logAssignment(assignment) {
// logging implementation
},
},
}).then(() => {
return setIsInitialized(true);
});
}, []);

if (!waitForInitialization || isInitialized) {
return children;
}
return loadingComponent;
}

After the SDK is initialized, you may assign variations from any child component of EppoRandomizationProvider. We recommend wrapping the SDK code in a useMemo hook to avoid invoking the assignment logic on every render:

<EppoRandomizationProvider>
<MyComponent />
</EppoRandomizationProvider>
function MyComponent(): JSX.Element {
const assignedVariation = useMemo(() => {
const eppoClient = getInstance();
return eppoClient.getStringAssignment("<FLAG-KEY>", "<SUBJECT-KEY>", <SUBJECT-ATTRIBUTES>, "<DEFAULT-VALUE>");
}, []);

return (
<div>
{assignedVariation === "<VARIATION-KEY>" && <p>Assigned control</p>}
</div>
);
}