1
votes

I need to integrate redux with an existing next project. but currently, I don´t understand how the store works server-side.

I´m following this example:

https://github.com/vercel/next.js/blob/canary/examples/with-redux/pages/ssg.js

export const initializeStore = (preloadedState) => {
  let _store = store ?? initStore(preloadedState)

  // After navigating to a page with an initial Redux state, merge that state
  // with the current state in the store, and create a new store
  if (preloadedState && store) {
    _store = initStore({
      ...store.getState(),
      ...preloadedState,
    })
    // Reset the current store
    store = undefined
  }

  // For SSG and SSR always create a new store
  if (typeof window === 'undefined') return _store
  // Create the store once in the client
  if (!store) store = _store

  return _store
}

Why a store is created in the server, I´m asking is because in the client also is created so, what store is finally used.

Why do I need to create an store in the server if in the client another totally different is created?

import { Provider } from 'react-redux'
import { useStore } from '../store'

export default function App({ Component, pageProps }) {
  const store = useStore(pageProps.initialReduxState)

  return (
    <Provider store={store}>
      <Component {...pageProps} />
    </Provider>
  )
}

The component definition below is also rendered in the client?

export function useStore(initialState) {
  const store = useMemo(() => initializeStore(initialState), [initialState])
  return store
}
1

1 Answers

1
votes

It is for SEO purpose. When client makes a request to the server, if you fetch the data on the server, populate the store and send this data to the client, search engine crawlers will see what is your website about, they can read what you have sent.

But you do not need to fully populate the store on the server. For example, let's say you have an admin page, and admin can access to users of your app or website. So when yo fetch data on the server, your server will ship a bunch of names to the client and this will not effect on your SEO results. In this case, in admin page component, inside "useEffect" you can dispatch action to get the list of users from the server.

Let's say you have an ecommerce website and in index page you are showing your products. In this case, it will be better to populate the store on the server so search engine crawlers can read your products and it helps your SEO results. To sync the store with the client you also have to dispatch "hydrate" action from the client to pass the data to the client side store. I think in your code "initializeStore()" is handling that.