Skip to content

Commit

Permalink
fix: avoid re-render on unchanged-context
Browse files Browse the repository at this point in the history
  • Loading branch information
T-Wizard committed Mar 9, 2023
1 parent 45341be commit 8b3b138
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
3 changes: 2 additions & 1 deletion apis/nucleus/src/components/NebulaApp.jsx
Expand Up @@ -33,7 +33,8 @@ const NebulaApp = forwardRef(({ initialContext, app }, ref) => {
}
},
setMuiThemeName,
setContext,
setContext: (ctx) =>
setContext((oldContext) => (JSON.stringify(oldContext) !== JSON.stringify(ctx) ? ctx : oldContext)),
getAppSelections: () => appSelections,
}));

Expand Down
52 changes: 52 additions & 0 deletions apis/nucleus/src/components/__tests__/nebulaapp.test.jsx
Expand Up @@ -193,4 +193,56 @@ describe('<NebulaApp />', () => {
act(() => ref.current.removeComponent(MyFoo));
expect(() => renderer.root.findByType(MyFoo)).toThrow();
});

test('setContext should trigger a new render of components using it if and only if it has changed', async () => {
let renderCount = 0;
const Foo = () => {
React.useContext(InstanceContext);
++renderCount;
return 'foo';
};
const MyFoo = <Foo key="1" />;
await render();
act(() => ref.current.addComponent(MyFoo));
expect(renderCount).toEqual(1);

// new context
act(() =>
ref.current.setContext({
keyboardNavigation: true,
constraints: {},
theme: 'classic',
language: 'pseudo',
deviceType: 'unit-test',
})
);
// increased render count
expect(renderCount).toEqual(2);

// same context
act(() =>
ref.current.setContext({
keyboardNavigation: true,
constraints: {},
theme: 'classic',
language: 'pseudo',
deviceType: 'unit-test',
})
);
// unchanged render count
expect(renderCount).toEqual(2);

// new context
act(() =>
ref.current.setContext({
keyboardNavigation: true,
constraints: { active: true },
theme: 'classic',
language: 'pseudo',
deviceType: 'unit-test',
})
);
// increased render count
expect(renderCount).toEqual(3);
});
});

0 comments on commit 8b3b138

Please sign in to comment.