From ac24f125ca7646cdbb440e7aa5c8de4e6be3205b Mon Sep 17 00:00:00 2001 From: Wojciech Maj Date: Wed, 25 Nov 2020 10:37:07 +0100 Subject: [PATCH] Refactor useTranslation to use useMemo instead of useState + useEffect --- src/useTranslation.js | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/src/useTranslation.js b/src/useTranslation.js index 9816a30..a726dd9 100644 --- a/src/useTranslation.js +++ b/src/useTranslation.js @@ -1,4 +1,4 @@ -import { useContext, useState, useEffect } from 'react'; +import { useContext, useMemo } from 'react'; import { Context } from './TProvider'; @@ -32,16 +32,13 @@ export default function useTranslation(string, args = {}) { const { languageFile } = context; - const [translatedString, setTranslatedString] = useState( - languageFile ? null : applyVars(string, args), - ); - - useEffect(() => { + const translatedString = useMemo(() => { const rawTranslatedString = getTranslatedString(languageFile, string); const stringWithArgs = applyVars(rawTranslatedString, args); - setTranslatedString(stringWithArgs); - }, [languageFile, string, ...Object.values(args)]); + return stringWithArgs; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [languageFile, string, ...JSON.stringify(args)]); return translatedString; } -- 2.54.0