next-i18next: Shallow routing does not work

Describe the bug

When switching the location with shallow routing option (using the Link or Router) it is not working (language does not switch).

Occurs in next-i18next version

Cloned from master branch (8.0.6).

Steps to reproduce

Simply add shallow={true} to the Link component in the example app

Expected behaviour

Change of language should also work with shallow routing

OS (please complete the following information)

  • Browser: Chrome 88.0.4324.190

Additional context

I can explain why this happens. With the current implementation of next-i18next the i18n instance is always completely replaced. The problem is that the t function of useTranslation is cached. So, if the components do not get recreated but just rerendered (as in shallow routing) the t is the old cached one even if the I18nextProvider has already a new i18n instance.

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 1
  • Comments: 15 (7 by maintainers)

Commits related to this issue

Most upvoted comments

Sure, feel free to investigate and let me know if we need to reopen this.

@isaachinman If i18next/react-i18next#1273 gets merged there is still a little problem why shallow routing does not work for next-i18next. When using shallow routing then getServerSideProps won’t be called again and appWithTranslation always uses a stale initialLocale to create the i18n client. To fix this the Next router must be queried for the correct locale. Here is a little code sample that would fix it in appWithTranslation.tsx:

const router = useRouter() // somewhere at the top
...
// changed stuff
locale = router.locale || initialLocale;

({ i18n } = createClient({
  ...createConfig({
    ...userConfig,
    lng: locale,
  }),
  lng: locale,
  resources: initialI18nStore,
}))