Skip to content

fix: Fixed redundant re-rendering issues #125

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Oct 1, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions src/Experiment.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
/// <reference types="jest" />
import * as React from 'react';
import * as Enzyme from 'enzyme';
import { act } from 'react-dom/test-utils';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new Adapter() });

Expand All @@ -30,8 +31,10 @@ describe('<OptimizelyExperiment>', () => {
const variationKey = 'variationResult';
let resolver: any;
let optimizelyMock: ReactSDKClient;
let isReady: boolean;

beforeEach(() => {
isReady = false;
const onReadyPromise = new Promise((resolve, reject) => {
resolver = {
reject,
Expand All @@ -51,7 +54,9 @@ describe('<OptimizelyExperiment>', () => {
id: 'testuser',
attributes: {},
},
isReady: jest.fn().mockReturnValue(false),
isReady: jest.fn().mockImplementation(() => isReady),
getIsReadyPromiseFulfilled: () => true,
getIsUsingSdkKey: () => true,
onForcedVariationsUpdate: jest.fn().mockReturnValue(() => {}),
} as unknown) as ReactSDKClient;
});
Expand Down Expand Up @@ -282,8 +287,8 @@ describe('<OptimizelyExperiment>', () => {

// Simulate client becoming ready
resolver.resolve({ success: true });

await optimizelyMock.onReady();
isReady = true;
await act(async () => await optimizelyMock.onReady());

component.update();

Expand Down Expand Up @@ -321,8 +326,8 @@ describe('<OptimizelyExperiment>', () => {

// Simulate client becoming ready
resolver.resolve({ success: true });

await optimizelyMock.onReady();
isReady = true;
await act(async () => await optimizelyMock.onReady());

component.update();

Expand Down
17 changes: 12 additions & 5 deletions src/Feature.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/
import * as React from 'react';
import * as Enzyme from 'enzyme';
import { act } from 'react-dom/test-utils';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new Adapter() });

Expand All @@ -27,11 +28,13 @@ describe('<OptimizelyFeature>', () => {
let resolver: any;
let optimizelyMock: ReactSDKClient;
const isEnabledMock = true;
let isReady: boolean;
const featureVariables = {
foo: 'bar',
};

beforeEach(() => {
isReady = false;
const onReadyPromise = new Promise((resolve, reject) => {
resolver = {
reject,
Expand All @@ -52,7 +55,9 @@ describe('<OptimizelyFeature>', () => {
id: 'testuser',
attributes: {},
},
isReady: jest.fn().mockReturnValue(false),
isReady: jest.fn().mockImplementation(() => isReady),
getIsReadyPromiseFulfilled: () => true,
getIsUsingSdkKey: () => true,
} as unknown) as ReactSDKClient;
});
it('throws an error when not rendered in the context of an OptimizelyProvider', () => {
Expand Down Expand Up @@ -209,7 +214,8 @@ describe('<OptimizelyFeature>', () => {
// Simulate client becoming ready
resolver.resolve({ success: true });

await optimizelyMock.onReady();
isReady = true;
await act(async () => await optimizelyMock.onReady());

component.update();

Expand All @@ -226,7 +232,7 @@ describe('<OptimizelyFeature>', () => {
}));

const updateFn = (optimizelyMock.notificationCenter.addNotificationListener as jest.Mock).mock.calls[0][1];
updateFn();
act(updateFn);

component.update();

Expand All @@ -253,7 +259,8 @@ describe('<OptimizelyFeature>', () => {
// Simulate client becoming ready
resolver.resolve({ success: true });

await optimizelyMock.onReady();
isReady = true;
await act(async () => await optimizelyMock.onReady());

component.update();

Expand All @@ -269,7 +276,7 @@ describe('<OptimizelyFeature>', () => {
foo: 'baz',
}));

updateFn();
act(updateFn);

component.update();

Expand Down
52 changes: 43 additions & 9 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ export interface ReactSDKClient extends Omit<optimizely.Client, 'createUserConte
setUser(userInfo: UserInfo): void;
onUserUpdate(handler: OnUserUpdateHandler): DisposeFn;
isReady(): boolean;
getIsReadyPromiseFulfilled(): boolean;
getIsUsingSdkKey(): boolean;

activate(
experimentKey: string,
Expand Down Expand Up @@ -165,27 +167,37 @@ class OptimizelyReactSDKClient implements ReactSDKClient {
id: null,
attributes: {},
};
private userPromiseResovler: (user: UserInfo) => void;
private userPromiseResolver: (user: UserInfo) => void;
private userPromise: Promise<OnReadyResult>;
private isUserPromiseResolved = false;
private onUserUpdateHandlers: OnUserUpdateHandler[] = [];
private onForcedVariationsUpdateHandlers: OnForcedVariationsUpdateHandler[] = [];

// Is the javascript SDK instance ready.
private isClientReady: boolean = false;

// We need to add autoupdate listener to the hooks after the instance became fully ready to avoid redundant updates to hooks
private isReadyPromiseFulfilled: boolean = false;

// Its usually true from the beginning when user is provided as an object in the `OptimizelyProvider`
// This becomes more significant when a promise is provided instead.
private isUserReady: boolean = false;

private isUsingSdkKey: boolean = false;

private readonly _client: optimizely.Client;

// promise keeping track of async requests for initializing client instance
private dataReadyPromise: Promise<OnReadyResult>;

private dataReadyPromiseFulfilled = false;

/**
* Creates an instance of OptimizelyReactSDKClient.
* @param {optimizely.Config} [config={}]
*/
constructor(config: optimizely.Config) {
this.initialConfig = config;

this.userPromiseResovler = () => {};
this.userPromiseResolver = () => {};

const configWithClientInfo = {
...config,
Expand All @@ -194,19 +206,39 @@ class OptimizelyReactSDKClient implements ReactSDKClient {
};
this._client = optimizely.createInstance(configWithClientInfo);

this.isClientReady = !!configWithClientInfo.datafile;
this.isUsingSdkKey = !!configWithClientInfo.sdkKey;

this.userPromise = new Promise(resolve => {
this.userPromiseResovler = resolve;
}).then(() => ({ success: true }));
this.userPromiseResolver = resolve;
}).then(() => {
this.isUserReady = true;
return { success: true }
});

this._client.onReady().then(() => {
this.isClientReady = true;
});

this.dataReadyPromise = Promise.all([this.userPromise, this._client.onReady()]).then(() => {
this.dataReadyPromiseFulfilled = true;

// Client and user can become ready synchronously and/or asynchronously. This flag specifically indicates that they became ready asynchronously.
this.isReadyPromiseFulfilled = true;
return {
success: true,
reason: 'datafile and user resolved',
};
});
}

getIsReadyPromiseFulfilled(): boolean {
return this.isReadyPromiseFulfilled;
}

getIsUsingSdkKey(): boolean {
return this.isUsingSdkKey;
}

onReady(config: { timeout?: number } = {}): Promise<OnReadyResult> {
let timeoutId: number | undefined;
let timeout: number = DEFAULT_ON_READY_TIMEOUT;
Expand Down Expand Up @@ -235,12 +267,13 @@ class OptimizelyReactSDKClient implements ReactSDKClient {
// TODO add check for valid user
if (userInfo.id) {
this.user.id = userInfo.id;
this.isUserReady = true;
}
if (userInfo.attributes) {
this.user.attributes = userInfo.attributes;
}
if (!this.isUserPromiseResolved) {
this.userPromiseResovler(this.user);
this.userPromiseResolver(this.user);
this.isUserPromiseResolved = true;
}
this.onUserUpdateHandlers.forEach(handler => handler(this.user));
Expand Down Expand Up @@ -275,7 +308,8 @@ class OptimizelyReactSDKClient implements ReactSDKClient {
}

isReady(): boolean {
return this.dataReadyPromiseFulfilled;
// React SDK Instance only becomes ready when both JS SDK client and the user info is ready.
return this.isUserReady && this.isClientReady;
}

/**
Expand Down
2 changes: 2 additions & 0 deletions src/hooks.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@ describe('hooks', () => {
attributes: {},
},
isReady: () => readySuccess,
getIsReadyPromiseFulfilled: () => true,
getIsUsingSdkKey: () => true,
onForcedVariationsUpdate: jest.fn().mockImplementation(handler => {
forcedVariationUpdateCallbacks.push(handler);
return () => {};
Expand Down
42 changes: 30 additions & 12 deletions src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,18 +210,24 @@ export const useExperiment: UseExperiment = (experimentKey, options = {}, overri

const finalReadyTimeout = options.timeout !== undefined ? options.timeout : timeout;
useEffect(() => {
if (!isClientReady) {
// Subscribe to initialzation promise only
// 1. When client is using Sdk Key, which means the initialization will be asynchronous
// and we need to wait for the promise and update decision.
// 2. When client is using datafile only but client is not ready yet which means user
// was provided as a promise and we need to subscribe and wait for user to become available.
if (optimizely.getIsUsingSdkKey() || !isClientReady) {
subscribeToInitialization(optimizely, finalReadyTimeout, initState => {
setState({
...getCurrentDecision(),
...initState,
});
});
}
}, [isClientReady, finalReadyTimeout, getCurrentDecision, optimizely]);
}, []);

useEffect(() => {
if (options.autoUpdate) {
// Subscribe to update after first datafile is fetched and readyPromise is resolved to avoid redundant rendering.
if (optimizely.getIsReadyPromiseFulfilled() && options.autoUpdate) {
return setupAutoUpdateListeners(optimizely, HookType.EXPERIMENT, experimentKey, hooksLogger, () => {
setState(prevState => ({
...prevState,
Expand All @@ -230,7 +236,7 @@ export const useExperiment: UseExperiment = (experimentKey, options = {}, overri
});
}
return (): void => {};
}, [isClientReady, options.autoUpdate, optimizely, experimentKey, getCurrentDecision]);
}, [optimizely.getIsReadyPromiseFulfilled(), options.autoUpdate, optimizely, experimentKey, getCurrentDecision]);

useEffect(
() =>
Expand Down Expand Up @@ -297,18 +303,24 @@ export const useFeature: UseFeature = (featureKey, options = {}, overrides = {})

const finalReadyTimeout = options.timeout !== undefined ? options.timeout : timeout;
useEffect(() => {
if (!isClientReady) {
// Subscribe to initialzation promise only
// 1. When client is using Sdk Key, which means the initialization will be asynchronous
// and we need to wait for the promise and update decision.
// 2. When client is using datafile only but client is not ready yet which means user
// was provided as a promise and we need to subscribe and wait for user to become available.
if (optimizely.getIsUsingSdkKey() || !isClientReady) {
subscribeToInitialization(optimizely, finalReadyTimeout, initState => {
setState({
...getCurrentDecision(),
...initState,
});
});
}
}, [isClientReady, finalReadyTimeout, getCurrentDecision, optimizely]);
}, []);

useEffect(() => {
if (options.autoUpdate) {
// Subscribe to update after first datafile is fetched and readyPromise is resolved to avoid redundant rendering.
if (optimizely.getIsReadyPromiseFulfilled() && options.autoUpdate) {
return setupAutoUpdateListeners(optimizely, HookType.FEATURE, featureKey, hooksLogger, () => {
setState(prevState => ({
...prevState,
Expand All @@ -317,7 +329,7 @@ export const useFeature: UseFeature = (featureKey, options = {}, overrides = {})
});
}
return (): void => {};
}, [isClientReady, options.autoUpdate, optimizely, featureKey, getCurrentDecision]);
}, [optimizely.getIsReadyPromiseFulfilled(), options.autoUpdate, optimizely, featureKey, getCurrentDecision]);

return [state.isEnabled, state.variables, state.clientReady, state.didTimeout];
};
Expand Down Expand Up @@ -373,18 +385,24 @@ export const useDecision: UseDecision = (flagKey, options = {}, overrides = {})

const finalReadyTimeout = options.timeout !== undefined ? options.timeout : timeout;
useEffect(() => {
if (!isClientReady) {
// Subscribe to initialzation promise only
// 1. When client is using Sdk Key, which means the initialization will be asynchronous
// and we need to wait for the promise and update decision.
// 2. When client is using datafile only but client is not ready yet which means user
// was provided as a promise and we need to subscribe and wait for user to become available.
if (optimizely.getIsUsingSdkKey() || !isClientReady) {
subscribeToInitialization(optimizely, finalReadyTimeout, initState => {
setState({
...getCurrentDecision(),
...initState,
});
});
}
}, [isClientReady, finalReadyTimeout, getCurrentDecision, optimizely]);
}, []);

useEffect(() => {
if (options.autoUpdate) {
// Subscribe to update after first datafile is fetched and readyPromise is resolved to avoid redundant rendering.
if (optimizely.getIsReadyPromiseFulfilled() && options.autoUpdate) {
return setupAutoUpdateListeners(optimizely, HookType.FEATURE, flagKey, hooksLogger, () => {
setState(prevState => ({
...prevState,
Expand All @@ -393,7 +411,7 @@ export const useDecision: UseDecision = (flagKey, options = {}, overrides = {})
});
}
return (): void => {};
}, [isClientReady, options.autoUpdate, optimizely, flagKey, getCurrentDecision]);
}, [optimizely.getIsReadyPromiseFulfilled(), options.autoUpdate, optimizely, flagKey, getCurrentDecision]);

return [state.decision, state.clientReady, state.didTimeout];
};