简体   繁体   中英

Persist data between two pages with Next.js

I would like to refactor my Next.js webapp to have different pages handle different screens. Currently, I have this component holding several states to know in which screen I'm in. In the jsx section, I'm using {value &&... } to render the right component.

But I feel this is not good design, and won't be maintainable when adding more and more screens.

I would also like to avoid Redux as it is overkill for my project.

I was thinking about persisting data in cookies so I can retrieve them with getInitialProps in every component when rendering a new page, but is there a more elegant way?

I've read about tweaking the _app.js but I'm not sure to understand the consequences of doing so, and how it could help me..

Any suggestion?

When multiple of your pages need to make use of same data, you can make use of Context to store the result. It a good way to make a centralized storage without using complex and more self sufficient libraries like redux

You can implement context inside of _app.js file which must reside inside your root folder. This way next.js treats it as a root wrapper and you would just need to use 1 instance of Context

contexts/appContext

import React from 'react';
const AppContext = React.createContext();
export const AppProvider = AppContext.Provider;
export const AppConsumer = AppContext.Consumer;
export default AppContext;

_app.js

import React from 'react'
import App from 'next/app'
import AppProvider from '../contexts/appContext';
class MyApp extends App {
  state={
    data:[]
  }
  render() {
    const { Component, pageProps } = this.props;
    // You can implement logic in this component to fetch data and update state
    return (
      <div>
        <AppProvider value={this.state.data}> // pass on value to context
          <Component {...pageProps} />
        </AppProvider>
      </div>
    )
  }
}
export default MyApp

Now further each component can make use of context value by using AppConsumer or using useContext if you use hooks

Please read more about how to use Context here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM