next.jsglobal-state

next.js how to manage global state with context in across multiple layouts


I'm using two layouts in next.js in accordance with per page layout structure.

in _app.js

import GlobalContext from "../utils/GlobalContext";
....
return getLayout(
    <Layout>
      <Component {...pageProps} />
    </Layout>
);

in page

Login.getLayout = function getLayout(page) {
    return (
        <Layout2>
            {page}
        </Layout2>
    )
}

global state seems to be reset when visiting a page with different layout.

problem is how to keep global state shared though the context on multiple layouts?


Solution

  • To share the global state shared among multiple templates we need to wrap the getLayout itself as below

    in _app.js

    return (
        <Layout>
          {getLayout(<Component {...pageProps} />)}
        </Layout>
    );