Redux setup with react
React comes with inbuilt state management for components using this.state and this.setState() so why do we need Redux:-
According to redux documentation, Redux is a state management library which can be used anywhere (React js, Angular js, jQuery, Vanilla js). But why do we need Redux with the React:-
React has state management for its component level and unidirectional data flow (data/state can be passed from parent to child components). Since react does not support data passing from child to parent so if you want to communicate data between sibling react components then it's a tricker work.
One way is:-
React Sibling components Communication flowHere for communication between ch1 (child 1) and ch2 (child 2), we need to pass data via parent component which is ok for a small application but when the component hierarchy increases then this way of communication between siblings is inappropriate and inefficient.
The second way is to use the context API. You can read more about react's context at https://blog.bitsrc.io/why-you-should-consider-the-new-context-api-in-react-a-deep-dive-d588b66c57b5
These both ways are tricker and only fit for the small level of applications. if the application and no of components increase then it's difficult to manage state with these both tricks. So to solve this issue redux is a great library.
You can read more about why to use redux with react at https://blog.logrocket.com/why-use-redux-reasons-with-clear-examples-d21bffd5835
So now will start our implementation for the react and redux setup:-
Our main goal here is to set up the redux with the react so you can use any react setup with create react app or you can use my blog React Js Environment Setup with WebPack @ https://medium.com/@kakarganpat/react-js-environment-setup-with-webpack-4787249bd5a0
The final setup is placed at my Github account @ https://github.com/Ganpatkakar/react-redux-seed
So now I hope that you already have the react setup and I will start by combining redux with react.
First, open your terminal and write below command:-
Redux uses store, reducers, and actions. The store is a read-only state and the only way to modify that via dispatching an action. The action will be a pure function and these actions will be caught by the reducers where the state will be modified as per the action payload. I know it is a little confusing but bear with me we will see all this with the examples below.
So lets setup store first:-
npm install --save redux react-redux
So we need to import redux for redux library and react-redux for connecting redux with the react.
Now create a file store.js inside src/redux/ and write below code in it -
import { createStore, applyMiddleware} from 'redux';
import commonReducer from "./reducers/commonReducer";
let initialState = {};
export default createStore(commonReducer, initialState);
Here we need to import createStore and applyMiddleware functions from redux library and commonReducer from reducers (we will create our reducer in a couple of minutes here below). Then we will assign empty object as an intialState for redux. If you have some data for initialState then you can provide here.
Then we will export our createStore function with parameters as reducer function and initial state. This function will return the store every time.
Let's connect our redux store to react.
index.js:-
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import store from "./redux/store";
import App from "./components/App";
const rootEl = document.getElementById("app");
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
rootEl
);
Need to import Provider from react-redux, the whole purpose of the Provider component is to provide the store to its all children components.
Get the store form our created redux store file.
Now to add more functionality to our react app we will create an App file inside the components folder.
App.js:-
import React, { Component } from 'react';
import myImage from "../assets/ganpat.jpg";
import { connect } from 'react-redux';
import {CommonAction} from '../redux/actions'
export class App extends Component {
render() {
return (
<React.Fragment>
<div>
App Loads Here
</div>
</React.Fragment>
)
}
}
export default App;
it's still not ready yet as it will give an error for the store file as we don't have commonReducer imported. So now let's create our commonReducer.js inside src/redux/reducers/commonReducer.js
export default function commonReducer(state = {}, action) {
switch (action.type) {
case "INITIAL_STATE":
return {
...state,
ready: action.payload
};
default:
return state
}
}
So here our reducer function will accept two parameters, default state, and action (I know you are thinking from where this action param will come, so bear with me for a couple of seconds will go to the redux third important part actions). Our actions need to return the action type and payload data. lets create our action and then we will come back to this reducer description later.
src/redux/actions/index.js
export function CommonAction (data) {
return { type: INITIAL_STATE, payload: data }
}
Thas our action, so the action is a pure component and it will return what it will get in the parameter.
Let's get back to reducer (commonReducer.js):-
Inside our reducer function, we need to verify check for the action type and take update the store according to our action.type. Redux always uses immutable store so whenever you update the store then always use the spread operator or Object.assign() function for store immutability. So why do we need immutable state-
Whenever the redux store updates then redux compare the previous store and update store. If there is any kind of changes then redux will update the store to react and react will update the components according to the new store props. The comparison between the previous store and update store is a complicated operation and to reduce the complexity redux uses the immutable store (immutable object operation will always return a new object with the new reference in memory).
In order to update state from react components we need to dispatch action from components, let's work on dispatching action from components:-
import React, { Component } from 'react';
import { connect } from 'react-redux';
import {CommonAction} from '../redux/actions'
export class App extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
this.props.CommonAction(true);
}
render() {
return (
<React.Fragment>
<div>
App Loads Here
</div>
</React.Fragment>
)
}
}
const mapStateToProps = (state) => ({
state: state
});
const mapDispatchToProps = dispatch => {
return {
CommonAction : (data) => dispatch(CommonAction(data))
}
};
export default connect(mapStateToProps, mapDispatchToProps)(App)
So we need to first connect our App component with redux using react-redux connect component. Connect function will accept two parameters as mapStateToProps and mapDispatchToProps. mapStateToProps will add redux store as props for the current component and mapDispatchToProps will add action to the props for the component. Connect component will return the function which will accept the current component App as a parameter.
We have imported CommonAction action from our /redux/actions/index.js file. We will dispatch this action on componentDidMount lifecycle method.
Now let's start our app using the command in terminal:-
npm start
So our webpage loads with text "App loads here".
Now how to test our Redux store:-
- For React setup you can use React Google chrome extension- https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en
- For Redux google chrome dev-tool extension- https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd?hl=en
- Now you need to update our redux store.js file as below:-
import { createStore, compose } from 'redux';
import commonReducer from "./reducers/commonReducer";
let initialState = {};
export default createStore(commonReducer,
initialState,
compose(window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__())
);
Now open y our chrome browser and go to localhost:5000, right click and inspect the application. You will find Redux tab, this the place where you can see all the actions dispatched and state changes.
Let's see our action "INITIAL_STATE" is present or not:-
Redux dev-tool extension screenshotHurrey!!! we have just configured and tested redux with react.
I have placed the similar or a little bit update code at my GitHub repository https://github.com/Ganpatkakar/react-redux-seed
If you have any kind of question please leave a comment below or you can contact me directly at kakarganpat@gmail.com.
If you like this post please don't forget to clap