Skip to content

Commit 557f32d

Browse files
authored
Fix context value reference changing across rendering (#196)
feat: fix context value reference change across render
1 parent e1e5c28 commit 557f32d

File tree

1 file changed

+28
-8
lines changed

1 file changed

+28
-8
lines changed

src/FlagProvider.tsx

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/** @format */
22

3-
import React, { type FC, type PropsWithChildren, useEffect, useMemo, useState } from 'react';
4-
import { type IConfig, UnleashClient } from 'unleash-proxy-client';
3+
import React, { type FC, type PropsWithChildren, useCallback, useEffect, useMemo, useState } from 'react';
4+
import { type IConfig, IMutableContext, UnleashClient } from 'unleash-proxy-client';
55
import FlagContext, { type IFlagContextValue } from './FlagContext';
66

77
export interface IFlagProvider {
@@ -106,20 +106,40 @@ const FlagProvider: FC<PropsWithChildren<IFlagProvider>> = ({
106106
};
107107
}, []);
108108

109+
const on = useCallback<IFlagContextValue['on']>(client.current.on, []);
110+
111+
const off = useCallback<IFlagContextValue['off']>(client.current.off, []);
112+
113+
const isEnabled = useCallback<IFlagContextValue['isEnabled']>(
114+
(toggleName: string) => client.current.isEnabled(toggleName),
115+
[]
116+
)
117+
118+
const updateContext = useCallback<IFlagContextValue['updateContext']>(
119+
async (context: IMutableContext) =>
120+
await client.current.updateContext(context),
121+
[]
122+
)
123+
124+
const getVariant = useCallback<IFlagContextValue['getVariant']>(
125+
(toggleName: string) => client.current.getVariant(toggleName),
126+
[]
127+
)
128+
109129
const context = useMemo<IFlagContextValue>(
110130
() => ({
111-
on: ((event, callback, ctx) => client.current.on(event, callback, ctx)) as IFlagContextValue['on'],
112-
off: ((event, callback) => client.current.off(event, callback)) as IFlagContextValue['off'],
113-
updateContext: async (context) => await client.current.updateContext(context),
114-
isEnabled: (toggleName) => client.current.isEnabled(toggleName),
115-
getVariant: (toggleName) => client.current.getVariant(toggleName),
131+
on,
132+
off,
133+
updateContext,
134+
isEnabled,
135+
getVariant,
116136
client: client.current,
117137
flagsReady,
118138
flagsError,
119139
setFlagsReady,
120140
setFlagsError,
121141
}),
122-
[flagsReady, flagsError]
142+
[flagsReady, flagsError, on, off, updateContext, isEnabled, getVariant]
123143
);
124144

125145
return (

0 commit comments

Comments
 (0)