How to Create a useTranslate Hook in React

How to Create a useTranslate Hook in React

Ferenc Almasi β€’ 2022 January 24 β€’ Read time 3 min read
  • twitter
  • facebook
React

To create a useTranslate hook in React that you can use for resolving translation keys, you first preferably want to create a context where you can store your translation keys to make it globally accessible in your React app:

Copied to clipboard! Playground
import React, { createContext } from 'react'

const translations = [
    {
        key: 'hello',
        value: 'Hello World! 🌎'
    }
]

export const TranslationContext = createContext([])

export const TranslationProvider = ({ children }) => (
    <TranslationContext.Provider value={translations}>
        {children}
    </TranslationContext.Provider>
)
context.js

All translations can be stored in an array of objects, with the key for the translation, and its translated value. Usually, you will fetch this data from your backend. Make sure you wrap your app into this context, so we can use it later in our custom useTranslate hook:

Copied to clipboard! Playground
import ReactDOM from 'react-dom'

import App from './App'
import { TranslationProvider } from './context'

ReactDOM.render(
    <TranslationProvider>
        <App />
    </TranslationProvider>,
    document.getElementById("root")
)
index.js
Wrap your App into the provider

Now let's create the actual hook in a new file:

Copied to clipboard! Playground
import React, { useContext } from 'react'
import { TranslationContext } from './context'

const useTranslate = () => {
    const context = useContext(TranslationContext)

    return (key, fallback) => {
        const translation = context?.find((translation) => translation.key === key)?.value

        return translation || fallback || key
    }
}

export default useTranslate
useTranslate.js

We need to use the built-in useContext hook here to consume the value coming from the TranslationContext. This hook returns another function that we can later call in our app with a translation key and a fallback text. To find a translation key, we can use Array.find, and search for the key that we can pass to this hook.

If there is a match, its value will be returned, otherwise, we can return a fallback text. If there is no fallback text either, we can return the translation key itself. To use this in your app, call the hook in the following way:

Copied to clipboard! Playground
import useTranslate from './useTranslate'

export default function App() {
    const translate = useTranslate()

    return (
        <div className="App">
            <h1>{translate('hello')}</h1>
            <h2>{translate('translation.unavailable', 'Showing fallback instead πŸ™Œ')}</h2>
            <h3>{translate('no.fallback.show.key.instead')}</h3>
        </div>
    )
}
App.js

If there is a match, it will show the translation. Otherwise, the hook will try to look for a fallback text. If it's not provided either, it will fall back to the translation. Now you can use a flag and request different translations from your backend to make your app multilingual. If you would like to tweak around with the project in one piece, try the hook on Codesandbox:

Try the hook on codesandbox
How to Create a useTranslate Hook in React
If you would like to see more Webtips, follow @flowforfrank

If you are interested in reading more about React hooks, see more examples for custom hooks or just learn about the basics, make sure to check out the article below.

All You Need to Know About React Hooks
  • twitter
  • facebook
React
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.