Skip to content
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

Avoid redundant re-rendering #1174

Merged
merged 1 commit into from
Sep 23, 2020
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
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);
});
});