Skip to content

Commit

Permalink
fix: memoize context value
Browse files Browse the repository at this point in the history
  • Loading branch information
takakobem committed Sep 23, 2020
1 parent afeaebb commit 7c83a8e
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 12 deletions.
14 changes: 9 additions & 5 deletions src/I18nextProvider.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import { createElement } from 'react';
import { createElement, useMemo } from 'react';
import { I18nContext } from './context';

export function I18nextProvider({ i18n, defaultNS, children }) {
const value = useMemo(
() => ({
i18n,
defaultNS,
}),
[i18n, defaultNS],
);
return createElement(
I18nContext.Provider,
{
value: {
i18n,
defaultNS,
},
value,
},
children,
);
Expand Down
33 changes: 26 additions & 7 deletions test/I18nextProvider.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,16 @@ const instance = {
};

describe('I18nextProvider', () => {
function TestComponent() {
const { t, i18n } = useTranslation('translation');
it('should render correct content', () => {
function TestComponent() {
const { t, i18n } = useTranslation('translation');

expect(typeof t).toBe('function');
expect(i18n).toBe(instance);
expect(typeof t).toBe('function');
expect(i18n).toBe(instance);

return <div>{t('key1')}</div>;
}
return <div>{t('key1')}</div>;
}

it('should render correct content', () => {
const wrapper = mount(
<I18nextProvider i18n={instance}>
<TestComponent />
Expand All @@ -44,4 +44,23 @@ describe('I18nextProvider', () => {
// console.log(wrapper.debug());
expect(wrapper.contains(<div>key1</div>)).toBe(true);
});

it('should not rerender if value is not changed', () => {
let count = 0;
const TestComponent = React.memo(function TestComponent() {
const { t } = useTranslation('translation');
count += 1;
return <div>{t('key1')}</div>;
});

const wrapper = mount(
<I18nextProvider i18n={instance}>
<TestComponent />
</I18nextProvider>,
{},
);
expect(count).toBe(1);
wrapper.setProps({ i18n: instance });
expect(count).toBe(1);
});
});

0 comments on commit 7c83a8e

Please sign in to comment.