Reputation: 301
I faced with some problem while developing Next.js application. It is rather an architectural issue.
I want to switch between routes, but keeping all the states on the page so that I can return to page without loosing it's state. I understand that I need to use initalProps at the top level. But this is only suitable for simple cases. Let's take an example where there're hundreds of states on a page with different levels of hierarchy. Is it possible to make a snapshot of all page states?
I look towards memo from React. Also, I think Redux would help me, but I don't use it in the application at all and it's one more dependency. Perhaps this can be solved using the Context Api.
Upvotes: 2
Views: 2093
Reputation: 6847
If you have global state that you need to share between different pages and the state is simple you can use Context API
, the Component
needs to be wrapped by the ContextProvider
in the custom app component in _app.js
.
The pseudo-code might look something like this for your use case,
// context and the provider component
export const MyContext = React.createContext();
export const MyCtxProvider = ({ children }) => {
// state logic
return (
<MyContext.Provider value={/* state value */}>
{children}
</MyContext.Provider>
)
}
in _app.js
import App from 'next/app'
import { MyCtxProvider } from './path-to-myctxprovider'
class MyApp extends App {
render() {
const { Component, pageProps } = this.props
return (
<MyCtxProvider>
<Component {...pageProps} />
</MyCtxProvider>
)
}
}
export default MyApp
Here is an example from nextjs repo that uses context API to share state between pages.
But if your global state is somewhat complex i.e. you want to keep both server state(fetched data from a remote API) and UI state in the global state, you might wanna use a state management system like redux
in this case. There are a lot of examples in the nextjs repo showing how to implement it. You can start from there.
Upvotes: 1
Reputation: 1259
As far as I understand, it will be an architectual problem. For global state management you need to use e.g: Redux, graphql, ContextAPI
, or give a global state to your app in pages/_app.js
. That will wrap your pages, and provide a cross pages state.(You can modify, and reuse that)
Opnion: Implement Redux
, if it"s really need. (for large amount of data in the state). Because it"s easier to implement, then remove it.
Other case: Use the inbuild ContextAPI
, or the pages/_app.js
state handler till it"s fit for your application.
Upvotes: 0