diff --git a/examples/next/next.config.js b/examples/next/next.config.js index ca05128..c141a30 100755 --- a/examples/next/next.config.js +++ b/examples/next/next.config.js @@ -2,7 +2,7 @@ /** @type {import('next').NextConfig} */ const nextConfig = { - reactStrictMode: true, + reactStrictMode: false, swcMinify: true, i18n: { locales: ['en', 'fr'], diff --git a/examples/next/pages/index.tsx b/examples/next/pages/index.tsx index 3b58d2e..ddfbb24 100644 --- a/examples/next/pages/index.tsx +++ b/examples/next/pages/index.tsx @@ -61,6 +61,6 @@ const Home = () => { }; // Comment this to disable SSR of initial locale -export const getStaticProps: GetStaticProps = getLocaleProps(); +// export const getStaticProps: GetStaticProps = getLocaleProps(); export default Home; diff --git a/packages/next-international/src/i18n/create-i18n-provider.tsx b/packages/next-international/src/i18n/create-i18n-provider.tsx index 931c3a6..d0c44f2 100644 --- a/packages/next-international/src/i18n/create-i18n-provider.tsx +++ b/packages/next-international/src/i18n/create-i18n-provider.tsx @@ -1,4 +1,4 @@ -import React, { Context, ReactElement, ReactNode, useEffect, useState } from 'react'; +import React, { Context, ReactElement, ReactNode, useCallback, useEffect, useRef, useState } from 'react'; import type { LocaleContext, Locales } from '../types'; import type { BaseLocale } from 'international-types'; import { useRouter } from 'next/router'; @@ -23,6 +23,7 @@ export function createI18nProvider( }: I18nProviderProps) { const { locale, defaultLocale, locales: nextLocales } = useRouter(); const [clientLocale, setClientLocale] = useState(); + const initialLoadRef = useRef(true); useEffect(() => { function checkConfigMatch([first, second]: [[string, string[]], [string, string[]]]) { @@ -42,15 +43,26 @@ export function createI18nProvider( checkConfigMatch([nextConfig, createI18n]); }, [nextLocales]); - useEffect(() => { - if (!locale || !defaultLocale) { - return; - } - + const loadLocale = useCallback((locale: string) => { locales[locale]().then(content => { setClientLocale(content.default as Locale); }); - }, [locale, defaultLocale]); + }, []); + + useEffect(() => { + // Initial page load + // Load locale if no baseLocale provided from getLocaleProps + if (!baseLocale && locale && initialLoadRef.current) { + loadLocale(locale); + } + + // Subsequent locale change + if (locale && !initialLoadRef.current) { + loadLocale(locale); + } + + initialLoadRef.current = false; + }, [baseLocale, loadLocale, locale]); if (!locale || !defaultLocale) { return error(`'i18n.defaultLocale' not defined in 'next.config.js'`);