Redux in Next JS project. | Technical

Image edited by Author using Canva.

Setting Up Next JS Project

The first and foremost step is that you should have a next js project at your disposal for practising the setup along with reading the tutorial as it will help you understand the concepts better.

npx create-next-app redis-next-tutorial

Installing Redux

Now once the basic code setup is done, our code is ready to take the react code and APIs. It's the right time that we can install redux to our code base using the following command.

npm i react-redux

Setting up store.js

Following is the code for setting up the global redux store. The redux store has the code where we use methods such as creating the store and applyMiddleware. The will help us initialise the global store that the components will be utilising.

import { createStore, applyMiddleware } from 'redux';
import { Middleware } from 'middlewares/index';
import { rootReducer } from 'reducers';
import { composeWithDevTools } from 'redux-devtools-extension';
const CombinedMiddleware = applyMiddleware(...Middleware);
export const store = createStore(
rootReducer,
composeWithDevTools(CombinedMiddleware)
);

Reducer

Let's create a reducer folder, where we will keep all the reducer-related code. Here you can check that we have the user combineReducers method which is used to combine all the sub-reducers.

import { combineReducers } from "redux";
import { auth } from "./auth";
export const rootReducer = combineReducers({
authReducer: auth
});

Connect Method

Once we are done with our redux setup, it's time to connect our component with the redux store.

import React from 'react';import { BrowserRouter } from "react-router-dom"import PropTypes from 'prop-types'import NavBar from 'containers/NavBar';import CustomRoutes from 'routes';
import Spinner from 'components/Spinner';
import { connect } from 'react-redux';
import './App.css';function App(props) {
return (
{/* Loader, when any api call is made */}
{props.loading && <Spinner />}
<div className="wrapper">
</div>
);
}
App.propTypes = {
loading: PropTypes.bool,
}
App.default = {
loading: false,
}
function mapStatesToProps(state) {
return {
loading: state.App.loading,
}
}
const mapDispatchToProps = {
}
export default connect(mapStatesToProps, mapDispatchToProps)(App);

Final Thoughts

So basically in this tutorial, all we have done is set up redux with our next js project. Now to make the project development ready you also need to implement either react-thunk or react-saga.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store