or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

components.mdhocs.mdhooks.mdicu-macro.mdindex.mdssr.md

hooks.mddocs/

0

# React Hooks

1

2

React i18next provides modern React hooks for accessing translation functionality in functional components with automatic re-rendering and type safety.

3

4

## Capabilities

5

6

### useTranslation Hook

7

8

The primary hook for accessing translation functions and i18next instance in React components. Automatically re-renders components when language changes or translations are updated.

9

10

```typescript { .api }

11

/**

12

* React hook providing translation function and i18next instance

13

* @param ns - Namespace(s) to load and use for translations

14

* @param options - Configuration options for the hook

15

* @returns Array/object with [t, i18n, ready] plus named properties

16

*/

17

function useTranslation<

18

const Ns extends FlatNamespace | $Tuple<FlatNamespace> | undefined = undefined,

19

const KPrefix extends KeyPrefix<FallbackNs<Ns>> = undefined

20

>(

21

ns?: Ns,

22

options?: UseTranslationOptions<KPrefix>

23

): UseTranslationResponse<FallbackNs<Ns>, KPrefix>;

24

25

interface UseTranslationOptions<KPrefix> {

26

/** Custom i18next instance (defaults to context or global instance) */

27

i18n?: i18n;

28

/** Enable React Suspense mode for async loading */

29

useSuspense?: boolean;

30

/** Prefix automatically added to all translation keys */

31

keyPrefix?: KPrefix;

32

/** Events to bind for re-rendering (default: 'languageChanged') */

33

bindI18n?: string | false;

34

/** Namespace resolution mode */

35

nsMode?: 'fallback' | 'default';

36

/** Target language override */

37

lng?: string;

38

}

39

40

type UseTranslationResponse<Ns extends Namespace, KPrefix> = [

41

t: TFunction<Ns, KPrefix>,

42

i18n: i18n,

43

ready: boolean

44

] & {

45

/** Translation function with type-safe keys */

46

t: TFunction<Ns, KPrefix>;

47

/** i18next instance for language changes and configuration */

48

i18n: i18n;

49

/** Indicates if translations are loaded and ready */

50

ready: boolean;

51

};

52

```

53

54

**Usage Examples:**

55

56

```typescript

57

import { useTranslation } from "react-i18next";

58

59

// Basic usage

60

function Welcome() {

61

const { t } = useTranslation();

62

return <h1>{t('welcome')}</h1>;

63

}

64

65

// With namespace

66

function UserProfile() {

67

const { t } = useTranslation('user');

68

return <div>{t('profile.title')}</div>;

69

}

70

71

// With key prefix

72

function Settings() {

73

const { t } = useTranslation('common', { keyPrefix: 'settings' });

74

return <button>{t('save')}</button>; // Resolves to 'common:settings.save'

75

}

76

77

// Multiple namespaces with fallback

78

function Dashboard() {

79

const { t, i18n, ready } = useTranslation(['dashboard', 'common']);

80

81

if (!ready) return <div>Loading...</div>;

82

83

return (

84

<div>

85

<h1>{t('title')}</h1>

86

<button onClick={() => i18n.changeLanguage('de')}>

87

{t('common:switchLanguage')}

88

</button>

89

</div>

90

);

91

}

92

93

// With interpolation and pluralization

94

function ItemCounter({ count }: { count: number }) {

95

const { t } = useTranslation();

96

return <p>{t('itemCount', { count })}</p>; // Handles plural forms

97

}

98

99

// Custom i18next instance

100

function IsolatedComponent({ i18nInstance }: { i18nInstance: i18n }) {

101

const { t } = useTranslation('isolated', { i18n: i18nInstance });

102

return <span>{t('message')}</span>;

103

}

104

```

105

106

### useSSR Hook

107

108

Hook for server-side rendering support that initializes i18next with pre-loaded translations and language settings.

109

110

```typescript { .api }

111

/**

112

* Initializes i18next instance with SSR data for hydration

113

* @param initialI18nStore - Pre-loaded translation resources from server

114

* @param initialLanguage - Initial language from server

115

* @param props - Additional options including custom i18next instance

116

*/

117

function useSSR(

118

initialI18nStore: Resource,

119

initialLanguage: string,

120

props?: { i18n?: i18n }

121

): void;

122

```

123

124

**Usage Examples:**

125

126

```typescript

127

import { useSSR, useTranslation } from "react-i18next";

128

129

// Next.js page component

130

function HomePage({ initialI18nStore, initialLanguage }) {

131

useSSR(initialI18nStore, initialLanguage);

132

const { t } = useTranslation();

133

134

return <h1>{t('welcome')}</h1>;

135

}

136

137

// With custom i18next instance

138

function CustomSSRComponent({ ssrData, customI18n }) {

139

useSSR(ssrData.store, ssrData.language, { i18n: customI18n });

140

const { t } = useTranslation();

141

142

return <div>{t('content')}</div>;

143

}

144

145

// In Next.js getServerSideProps or getStaticProps

146

export async function getServerSideProps(context) {

147

const { initialI18nStore, initialLanguage } = getInitialProps();

148

149

return {

150

props: {

151

initialI18nStore,

152

initialLanguage

153

}

154

};

155

}

156

```

157

158

## Type Definitions

159

160

```typescript { .api }

161

// Namespace resolution types

162

type FallbackNs<Ns> = Ns extends undefined

163

? TypeOptions['defaultNS']

164

: Ns extends Namespace

165

? Ns

166

: TypeOptions['defaultNS'];

167

168

// Conditional hook signature based on i18next selector support

169

type UseTranslationHook = TypeOptions['enableSelector'] extends true | 'optimize'

170

? UseTranslationSelector

171

: UseTranslationLegacy;

172

173

interface UseTranslationLegacy {

174

<

175

const Ns extends FlatNamespace | $Tuple<FlatNamespace> | undefined = undefined,

176

const KPrefix extends KeyPrefix<FallbackNs<Ns>> = undefined

177

>(

178

ns?: Ns,

179

options?: UseTranslationOptions<KPrefix>

180

): UseTranslationResponse<FallbackNs<Ns>, KPrefix>;

181

}

182

183

interface UseTranslationSelector {

184

<

185

const Ns extends FlatNamespace | $Tuple<FlatNamespace> | undefined = undefined,

186

const KPrefix = undefined

187

>(

188

ns?: Ns,

189

options?: UseTranslationOptions<KPrefix>

190

): UseTranslationResponse<FallbackNs<Ns>, KPrefix>;

191

}

192

193

// SSR resource type from i18next

194

interface Resource {

195

[language: string]: {

196

[namespace: string]: any;

197

};

198

}

199

```

200

201

## Hook Behavior

202

203

### Re-rendering Triggers

204

205

The `useTranslation` hook automatically triggers component re-renders when:

206

207

- Language changes via `i18n.changeLanguage()`

208

- Translations are added or updated via `i18n.addResource()` or `i18n.addResourceBundle()`

209

- Namespace loading completes

210

- Custom events specified in `bindI18n` option

211

212

### Suspense Support

213

214

When `useSuspense: true` (default), the hook integrates with React Suspense:

215

216

- Component suspends during translation loading

217

- Resumes rendering when resources are ready

218

- Set `useSuspense: false` for manual loading state handling

219

220

### Error Handling

221

222

The hook handles common error scenarios:

223

224

- Missing i18next instance: Returns fallback translation function

225

- Missing translations: Falls back to key or default values

226

- Network errors: Continues with cached or fallback translations

227

- Invalid namespaces: Logs warnings and continues with available namespaces