Hire Me

Next.js and Redux - State Management Made Easy

Updated: 07/01/2023

Setting up Redux in Next.js

To integrate Redux into your Next.js application, follow these steps:

  • Install the necessary dependencies. You will need redux, react-redux, and redux-thunk to set up Redux and handle asynchronous actions.
npm install redux react-redux redux-thunk
  • Create a Redux store and wrap your Next.js application with the Provider component from react-redux.
// pages/_app.js import { Provider } from "react-redux"; import { createWrapper } from "next-redux-wrapper"; import { createStore, applyMiddleware } from "redux"; import thunkMiddleware from "redux-thunk"; import rootReducer from "../reducers"; const store = createStore(rootReducer, applyMiddleware(thunkMiddleware)); const MyApp = ({ Component, pageProps }) => ( <Provider store={store}> <Component {...pageProps} /> </Provider> ); export default createWrapper(() => store).withRedux(MyApp);
  • Create your Redux actions, reducers, and selectors as per your application's needs. You can use the Redux toolkit or write them from scratch.
// actions.js export const incrementCounter = () => { return { type: "INCREMENT_COUNTER", }; }; // reducers.js const initialState = { counter: 0, }; const counterReducer = (state = initialState, action) => { switch (action.type) { case "INCREMENT_COUNTER": return { ...state, counter: state.counter + 1, }; default: return state; } }; export default counterReducer; // selectors.js export const selectCounter = (state) => state.counter;
  • Use the Redux state and dispatch actions in your Next.js components using the useSelector and useDispatch hooks from react-redux.
// components/Counter.js import { useSelector, useDispatch } from "react-redux"; import { incrementCounter } from "../actions"; import { selectCounter } from "../selectors"; const Counter = () => { const counter = useSelector(selectCounter); const dispatch = useDispatch(); const handleIncrement = () => { dispatch(incrementCounter()); }; return ( <div> <p>Counter: {counter}</p> <button onClick={handleIncrement}>Increment</button> </div> ); }; export default Counter;

Conclusion

Next.js and Redux make state management easy and efficient for your Next.js applications. In this blog post, we explored how to set up Redux in a Next.js application using react-redux, create the Redux store, actions, reducers, and selectors, and use the Redux state within Next.js components using hooks.

With Redux, you can centralize and control the state of your application, making it easier to develop and maintain complex Next.js projects.