|
1 | 1 | 'use client';
|
2 | 2 |
|
3 |
| -import { type ReactNode } from 'react'; |
| 3 | +import { type ReactNode, useMemo } from 'react'; |
4 | 4 | import { useRouter, usePathname } from 'next/navigation';
|
5 | 5 | import {
|
6 |
| - useI18n, |
7 | 6 | type Translations,
|
8 | 7 | I18nContext,
|
9 | 8 | defaultTranslations,
|
@@ -40,35 +39,40 @@ export function I18nProvider({
|
40 | 39 | locale,
|
41 | 40 | ...props
|
42 | 41 | }: I18nProviderProps) {
|
43 |
| - const context = useI18n(); |
44 | 42 | const router = useRouter();
|
45 | 43 | const pathname = usePathname();
|
46 | 44 |
|
47 |
| - const onChange = useEffectEvent((value: string) => { |
48 |
| - const segments = pathname.split('/').filter((v) => v.length > 0); |
| 45 | + const onChange = |
| 46 | + props.onChange ?? |
| 47 | + // eslint-disable-next-line react-hooks/rules-of-hooks -- always controlled |
| 48 | + useEffectEvent((value: string) => { |
| 49 | + const segments = pathname.split('/').filter((v) => v.length > 0); |
49 | 50 |
|
50 |
| - // If locale prefix hidden |
51 |
| - if (segments[0] !== locale) { |
52 |
| - segments.unshift(value); |
53 |
| - } else { |
54 |
| - segments[0] = value; |
55 |
| - } |
| 51 | + // If locale prefix hidden |
| 52 | + if (segments[0] !== locale) { |
| 53 | + segments.unshift(value); |
| 54 | + } else { |
| 55 | + segments[0] = value; |
| 56 | + } |
56 | 57 |
|
57 |
| - router.push(`/${segments.join('/')}`); |
58 |
| - router.refresh(); |
59 |
| - }); |
| 58 | + router.push(`/${segments.join('/')}`); |
| 59 | + router.refresh(); |
| 60 | + }); |
60 | 61 |
|
61 | 62 | return (
|
62 | 63 | <I18nContext.Provider
|
63 |
| - value={{ |
64 |
| - locale, |
65 |
| - locales, |
66 |
| - text: { |
67 |
| - ...context.text, |
68 |
| - ...props.translations, |
69 |
| - }, |
70 |
| - onChange: props.onChange ?? onChange, |
71 |
| - }} |
| 64 | + value={useMemo( |
| 65 | + () => ({ |
| 66 | + locale, |
| 67 | + locales, |
| 68 | + text: { |
| 69 | + ...defaultTranslations, |
| 70 | + ...props.translations, |
| 71 | + }, |
| 72 | + onChange, |
| 73 | + }), |
| 74 | + [locale, locales, onChange, props.translations], |
| 75 | + )} |
72 | 76 | >
|
73 | 77 | {props.children}
|
74 | 78 | </I18nContext.Provider>
|
|
0 commit comments