Skip to content

i18next-hmr not re-rendering React components when updating the contents of the translations JSON files #230

@utksaxena

Description

@utksaxena

Describe the bug
I have setup the i18next config file like so:

import { initReactI18next } from 'react-i18next'

import i18n from 'i18next'
import LanguageDetector from 'i18next-browser-languagedetector'
import { HMRPlugin } from 'i18next-hmr/plugin'
import Backend from 'i18next-http-backend'

const DEFAULT_LANGUAGE = 'en'

let i18nChain = i18n.use(Backend).use(LanguageDetector).use(initReactI18next)

const isDevelopment = process.env.NODE_ENV === 'development'

if (isDevelopment) {
  i18nChain = i18nChain.use(
    new HMRPlugin({
      vite: {
        client: true, // enables client side HMR in Vite
      },
    })
  )
}

void i18nChain.init({
  // Fallback locale used when a translation is
  // missing in the active locale.
  fallbackLng: DEFAULT_LANGUAGE,

  detection: {
    // Only detect from browser, don't use querystring/cookies/etc.
    order: ['navigator'],
    // Cache detected language in localStorage
    caches: ['localStorage'],
  },

  supportedLngs: ['en'],
  load: 'languageOnly',

  // Default namespace for app-wide translations
  defaultNS: 'common',
  // Only preload 'common' namespace; route-specific namespaces load on-demand
  ns: ['common'],

  // Global fallback: all namespaces fall back to 'common' when a key is missing
  fallbackNS: 'common',

 // IMPORTANT
  react: {
    ...(isDevelopment ? { bindI18nStore: 'added removed' } : {}),
  },

  backend: {
    // public/locales/...
    loadPath: '/locales/{{lng}}/{{ns}}.json',
  },
})

export default i18n

I need to add the react > bindI18nStore to get the React components to re-render on translations content change in JSON files. This feels like a workaround and I assume I shouldn't need to do this when using i18next-hmr in my Vite config as shown below:

...
...

export default defineConfig(({ mode }) => {
  const developmentPlugins = [
    i18nextHMRPlugin({
      localesDir: 'public/locales',
    }),
  ]

  setEnv(mode)
  return {
    plugins: [
      ...,
      ...,
     ...developmentPlugins,
  }
})
...
...

To Reproduce
Steps to reproduce the behavior:

  1. Change a value in common.json translations file.
  2. Notice that while the translations are reloaded (console.logs show up for the reloading of translations), the React component does not update to show the updated value.

Expected behavior
UI should update to show the u[dated value.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions