I am building a website, which has two languages, so I persist the selected language on cookie and retrieve it in the getInitialProps at _app file then pass it as a context API value. and I keep the cookie with sync to language state through the useEffect. the _app.js file look like this.
import React, { useState, useEffect } from 'react';
import nextCookie from 'next-cookies';
import * as Cookie from 'js-cookie';
import Head from 'next/head';
import { ThemeProvider } from 'emotion-theming';
import Layout from '../components/Common/Layout';
import GlobalStyle from '../components/GlobalStyle';
import { languageState, languageDispatch } from '../hooks/useLanguage';
function MyApp({ Component, pageProps, initialLanguage = 'ar' }) {
const [language, setLanguage] = useState(initialLanguage);
const changeLanuage = () => {
setLanguage((prev) => (prev == 'en' ? 'ar' : 'en'));
};
useEffect(() => {
Cookie.set('language', language);
}, [language]);
return (
<languageDispatch.Provider value={changeLanuage}>
<languageState.Provider value={language}>
<ThemeProvider theme={theme}>
<Layout>
<Head>
<link rel="shortcut icon" href="/svg/favicon.ico" />
</Head>
<Component {...pageProps} />
<GlobalStyle rtl={rtl} />
</Layout>
</ThemeProvider>
</languageState.Provider>
</languageDispatch.Provider>
);
}
MyApp.getInitialProps = async ({ ctx }) => {
const { language } = cookies(ctx);
return { initialLanguage: language };
};
in the development mode and deploying on now, it works perfectly with each page refresh. However, when I export it as static and deploy it on Netlify, with each refresh the language returns to its initial value ("ar").
Is there a better way to implement it, if no, what's wrong with the above implementation?