Skip to content

Commit

Permalink
fix: stabilize t in app directory
Browse files Browse the repository at this point in the history
  • Loading branch information
jessemartin committed Apr 1, 2024
1 parent 335c039 commit a851d30
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 8 deletions.
30 changes: 29 additions & 1 deletion __tests__/useTranslation.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState } from 'react'
import React, { useEffect, useState } from 'react'
import { render, cleanup, fireEvent } from '@testing-library/react'
import I18nProvider from '../src/I18nProvider'
import useTranslation from '../src/useTranslation'
Expand Down Expand Up @@ -1549,5 +1549,33 @@ describe('useTranslation', () => {
const { container } = render(<Inner />)
expect(container.textContent).toContain(expected)
})

test('`t` is stable', () => {
const Inner = ({ effect }) => {
const { t } = useTranslation()

useEffect(() => {
const text = t('ns:interpolation', {
count: 3,
})
effect(text)
}, [effect, t])
}

globalThis.__NEXT_TRANSLATE__ = {
namespaces: {
ns: {
interpolation: 'There are {{count}} cats.',
},
},
lang: 'en',
config: {},
}

const effect = jest.fn()
const { rerender } = render(<Inner effect={effect} />)
rerender(<Inner effect={effect} />)
expect(effect).toBeCalledTimes(1)
})
})
})
22 changes: 15 additions & 7 deletions src/useTranslation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,26 @@ function useTranslationInPages(defaultNS?: string): I18n {
)
}

function isServer() {
return typeof window === 'undefined'
}

function useTranslationAppDir(defaultNS?: string) {
const { lang, namespaces, config } = globalThis.__NEXT_TRANSLATE__ ?? {}
const localesToIgnore = config.localesToIgnore || ['default']
const ignoreLang = localesToIgnore.includes(lang)
const t = transCore({
config,
allNamespaces: namespaces,
pluralRules: new Intl.PluralRules(ignoreLang ? undefined : lang),
lang,
})
const getT = () => {
const t = transCore({
config,
allNamespaces: namespaces,
pluralRules: new Intl.PluralRules(ignoreLang ? undefined : lang),
lang,
})

return { t: wrapTWithDefaultNs(t, defaultNS), lang }
return wrapTWithDefaultNs(t, defaultNS)
}
const t = isServer() ? getT() : useMemo(getT, [defaultNS])
return { t, lang }
}

export default function useTranslation(defaultNS?: string): I18n {
Expand Down

0 comments on commit a851d30

Please sign in to comment.