Skip to content

Commit 57622df

Browse files
authored
Update README with React usage example
1 parent 16ab7f3 commit 57622df

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

README.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,52 @@ This SDK is for client-side JS applications that run in a web browser. For serve
88
## Getting Started
99

1010
Refer to our [SDK documentation](https://docs.geteppo.com/feature-flagging/randomization-sdk) for how to install and use the SDK.
11+
12+
## Usage with React
13+
14+
For usage in React applications, we recommend creating a [Context](https://reactjs.org/docs/context.html) provider to intialize the SDK and store the initialization status.
15+
16+
```tsx
17+
import { useEffect, useState, createContext } from 'react';
18+
import * as EppoSdk from '@eppo/js-client-sdk';
19+
20+
const EppoContext = createContext({ isInitialized: false });
21+
22+
function EppoProvider({ children }): JSX.Element {
23+
const [isInitialized, setIsInitialized] = useState(false);
24+
25+
useEffect(() => {
26+
EppoSdk.init({ apiKey: '<API-KEY>' })
27+
.then(() => setIsInitialized(true));
28+
}, []);
29+
30+
return (
31+
<EppoContext.Provider value={{ isInitialized }}>
32+
{children}
33+
</EppoContext.Provider>
34+
);
35+
}
36+
```
37+
38+
Use the context provider at the root of your component tree to wrap the rest of your application:
39+
40+
```tsx
41+
<EppoProvider>
42+
<MyApp />
43+
</EppoProvider>
44+
```
45+
46+
React components in your application should consume the context to check that the SDK has been initialized before assigning a variation. (Alternatively, you could have the `EppoProvider` wait to render its children until the SDK is initialized.)
47+
48+
```tsx
49+
import { useContext } from 'react';
50+
import * as EppoSdk from '@eppo/js-client-sdk';
51+
52+
const { isInitialized } = useContext(EppoContext);
53+
if (isInitialized) {
54+
const assignedVariation = EppoSdk.getInstance().getAssignment(subjectKey, experimentKey);
55+
...
56+
}
57+
```
58+
59+

0 commit comments

Comments
 (0)