Skip to content

Instantly share code, notes, and snippets.

@3nvi

3nvi/pageContext.jsx

Last active Nov 12, 2020
Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@marcomelilli marcomelilli commented Jul 16, 2020

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

This comment has been minimized.

Copy link
Owner Author

@3nvi 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