I have seen next.js example to use redux. But is there any easy way to setup redux with next.js? I want to setup redux how i used to setup with react.js
-
Does this answer your question? Using react redux with next.jsShankar Ganesh Jayaraman– Shankar Ganesh Jayaraman2020-12-23 08:40:52 +00:00Commented Dec 23, 2020 at 8:40
-
I wanted a solution with npx create-next-app and similar setup how i used to with react. Now i can do it. and shared my answer here too.Nasir Khan– Nasir Khan2020-12-23 09:07:30 +00:00Commented Dec 23, 2020 at 9:07
-
stackoverflow.com/questions/52095681/…Yilmaz– Yilmaz2022-04-16 14:10:06 +00:00Commented Apr 16, 2022 at 14:10
5 Answers
Assuming you have knowledge in Redux with React.
Firstly, install these packages
$ npm install next-redux-wrapper react-redux redux redux-thunk --save
$ npm install redux-devtools-extension --save-dev
Override or create the default App, create the file ./pages/_app.js as shown below:
import withRedux from 'next-redux-wrapper'
import { Provider } from 'react-redux'
import { withRouter } from 'next/router'
import App from 'next/app'
import createStore from 'store/createStore'
class MyApp extends App {
render () {
const { Component, pageProps, router, store } = this.props
return (
<Provider store={store}>
<Component router={router} {...pageProps} />
</Provider>
)
}
}
export default withRedux(createStore)(
withRouter(MyApp)
)
In your pages/component, you can use Redux as you do normally.
1 Comment
https://github.com/vercel/next.js/tree/canary/examples/with-redux-wrapper
cant get any easier than this
2 Comments
Here is my simplest way, you can follow it. https://github.com/imimran/next-redux-example
Comments
I would recommend using redux toolkit because it reduces boilerplate code in redux...
With createSlice you create Action and Reducer at the same time. And in case of dispatching API calls to the backend and performing suitable state mutations for pending, fulfilled and rejected API calls, createAsyncThunk is the Best!
As per my personal experience, if you are asking this question just for initial learning, then your first setup that you attached as an answer is enough but for a real App, so should definitely go with Redux Toolkit. You can check this sandbox example
Comments
First i created simple next.js app with "npx create-next-app" Then i installed "npm i redux react-redux redux-thunk redux-devtools-extension
Then I created general redux setup in a folder called "store" and folder structure is like the following image and code is for store.js
Code is for reducer > index.js

FINALLY created a _app.js file in pages folder and code is like this

If anyone still have question about setup please let me know...
