Skip to content

Instantly share code, notes, and snippets.

@3nvi
Last active June 20, 2023 03:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save 3nvi/91db00834bfd52bc4d8f0b29bf836c6b to your computer and use it in GitHub Desktop.
Save 3nvi/91db00834bfd52bc4d8f0b29bf836c6b to your computer and use it in GitHub Desktop.
import React from 'react';
import { useTranslation } from 'react-i18next';
const PageContext = React.createContext({});
export const PageContextProvider = ({ pageContext, children }) => {
const { i18n } = useTranslation();
i18n.changeLanguage(pageContext.lang);
return <PageContext.Provider value={pageContext}>{children}</PageContext.Provider>;
};
export const usePageContext = () => React.useContext(PageContext);
@marcomelilli
Copy link

Fixes:

  • const PageContext = React.createContext({});

  • return <PageContext.Provider value={pageContext}>{children}</PageContext.Provider>;

And I added a check:
if(i18n.language != pageContext.lang) i18n.changeLanguage(pageContext.lang);
otherwise I have the following error: 'Too many re-renders. React limits the number of renders to prevent an infinite loop.'

@3nvi
Copy link
Author

3nvi commented Nov 12, 2020

For some reason I missed this comment for so long. Thanks so much for this, I've updated this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment