Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Managing user's global state on next.js application

Tags:

I am coming from the world of SPA's and REST/GraphQl API's. Now I am building personal project with Next.js library for SSR(Server Side Rendered) React App.

Since I used Redux in all of my single page Apps, I'm now wondering how should I manage user state when every route user visits, a new link is loaded and the page has been refreshed.

I found some info about sessions and cookies, but neither of those are familiar to me. I looked at some online articles about using Redux with Next.js but it seems complicated.

like image 202
Pavle Avatar asked Jul 12 '19 19:07

Pavle


People also ask

How do you maintain a state in NextJS?

One of the most common ways to manage state is with the useState Hook. We will build an application that lets you increase the score by clicking the button. We first imported the useState hook itself, then set the initial state to be 0 . We also provided a setScore function so we can update the score later.

How do I keep component state across pages in NextJS?

In Next. js, the correct way to persist components between page changes is to use the custom App component. It's quite simple. All you have to do is to create the file /pages/_app.

Can I use redux in NextJS?

Can I use Next. js with Redux? Yes! Here's an example with Redux and an example with thunk.

Is NextJS client-side rendering?

By default, Next. js pre-renders every page. This means that Next. js generates HTML for each page in advance, instead of having it all done by client-side JavaScript.


2 Answers

Let's simplify how Next works, browser sends a request to the server, Next renders on server side, returns an html, then, Next re-hydrate the page, and from now it behaves as SPA.

Next has an example folder basically for every technology including redux.

Checkout the redux example.

like image 177
felixmosh Avatar answered Sep 22 '22 13:09

felixmosh


If you're used to doing it in a route-based way, this may help understand:

  1. the whole app (_app.js) is wrapped in the Provider for redux, so all pages and components in the app can access the store.
  2. according to the docs:
    otherwise different user data can be mixed up. On the client side the same store is used, even between page changes.``` 
  3. So your app will recreate the store on every request, but pass the request, the url, and possibly even the results (of the request) into the initial state of the store, so each page and component can utilize the store before rendering.
  4. also checkout getInitialProps which will perform some sideEffect before the components on a page renders, and provide data to the page's props.

some resources:

  • https://github.com/zeit/next.js/tree/canary/examples/with-redux
  • https://medium.com/@bhavikbamania/a-beginner-guide-for-redux-with-next-js-4d018e1342b2
like image 36
K.H. B Avatar answered Sep 22 '22 13:09

K.H. B