I started integrated nextjs to my react app, when I tried to make configuration for redux, but I found that it requires additional configuration for store like get preloadState and other stuff If someone makes a favor for me explains it to me setup by step coz I don't like to copy and past without understanding to be easier for me to edit and maintain
function initStore(preloadedState = initialState) {
return createStore(
reducer,
preloadedState,
composeWithDevTools(applyMiddleware())
)
}
export const initializeStore = (preloadedState) => {
let _store = store ?? initStore(preloadedState)
if (preloadedState && store) {
_store = initStore({
...store.getState(),
...preloadedState,
})
store = undefined
}
if (typeof window === 'undefined') return _store
if (!store) store = _store
return _store
}
export function useStore(initialState) {
const store = useMemo(() => initializeStore(initialState), [initialState])
return store
}
With nextjs you can prefetch stuff before rendering the page, by using getServerSideProps or getStaticProps functions.
Basically, that code is checking before initializing the store if there's already something in the store, if there's something it will try to merge it with the initial store values, if not it will just return the initial state of the store.
There's some validation to check if you're not running this from the browser:
if (typeof window === 'undefined') return _store
This typically means that you're using the redux store in a data fetching function of nextjs like in this example https://github.com/vercel/next.js/blob/canary/examples/with-redux/pages/ssr.js.
Also the useStore function is memoizing the state to see if it should re run initializeStore, only if the initial state changes.