Commit 405d61d
authored
fix: memoize React client to provide stability (#1276)
## This PR
👋 Maybe I'm missing something, but `useOpenFeatureClient` currently
returns an unstable `client` that is recreated every time the provider
re-renders, if you pass a domain into the provider instead of a specific
client.
This PR wraps the creation of that client when a domain is passed in
`useMemo`, which should ensure that it is then stable for downstream
usage via the `useOpenFeatureClient` hook.
As an example, due to `client` being unstable (combined with the
`shouldRunNow` behaviour in the client), this logs `ready` every time
the provider re-renders rather than just once when the client is
actually ready.
```ts
const client = useOpenFeatureClient();
useEffect(() => {
const ready = () => {
console.log('ready');
};
client.addHandler(ProviderEvents.Ready, ready);
return () => {
client.removeHandler(ProviderEvents.Ready, ready);
};
}, [client]);
```
The closest workaround I've found currently is checking if the domain
matches w/ `useState` + `useEffect`:
```ts
const client = useOpenFeatureClient();
const [stableClient, setStableClient] = useState(client);
useEffect(() => {
setStableClient((existing) => (existing.metadata.domain === client.metadata.domain ? existing : client));
}, [client]);
useEffect(() => {
const ready = () => {
console.log('ready');
};
stableClient.addHandler(ProviderEvents.Ready, ready);
return () => {
stableClient.removeHandler(ProviderEvents.Ready, ready);
};
}, [stableClient]);
---------
Signed-off-by: Matt Cowley <me@mattcowley.co.uk>
Signed-off-by: MattIPv4 <me@mattcowley.co.uk>1 parent 27666b8 commit 405d61d
File tree
2 files changed
+16
-4
lines changed- packages/react
- src/provider
- test
2 files changed
+16
-4
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
32 | 32 | | |
33 | 33 | | |
34 | 34 | | |
35 | | - | |
36 | | - | |
37 | | - | |
| 35 | + | |
38 | 36 | | |
39 | | - | |
| 37 | + | |
40 | 38 | | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
78 | 78 | | |
79 | 79 | | |
80 | 80 | | |
| 81 | + | |
| 82 | + | |
| 83 | + | |
| 84 | + | |
| 85 | + | |
| 86 | + | |
| 87 | + | |
| 88 | + | |
| 89 | + | |
| 90 | + | |
| 91 | + | |
| 92 | + | |
| 93 | + | |
| 94 | + | |
81 | 95 | | |
82 | 96 | | |
83 | 97 | | |
| |||
0 commit comments