Redux in React JS

Redux in React JS:  Do you have heard about Redux? Redux is a predictable state container for JavaScript apps. It helps us to write applications that behave consistently, run in different environments (such as client, server, and native), and are easy to test. On top of that, it provides a great developer experience, such as live code editing combined with time-traveling debugger You can use Redux together with React, or with any other view library. Redux is very tiny (2kB, including dependencies).
Redux is created by Dan Abramov, Who works at Facebook. Redux is not for ReactJS, Redux is for the whole JavaScript. Redux is inspired by Facebook’s Flux and influenced by functional programming language Elm.

Principles of Redux

There are 3 main principles of Redux, they are following

Single Source Of Truth

The state of our whole application is stored in one object. Our whole application depends on only one object. Which makes easier to understand and make changes to our states. We can call it a single tree. A single state tree also makes it easier to debug or inspect an app.

Single Source Of Truth Example

console.log(store.getState())
/* Prints
{
visibilityFilter: 'SHOW_ALL',
todos:
{
text: 'Consider using Redux',
completed: true,
},
{
text: 'Keep all state in a single tree',
completed: false
}
]
}
*/

State Is Read Only

You cannot write state, meaning that you can not mutate state directly. The state is something we should read and pass it to ReactJS components. When we say, we cannot change state directly how do we change data inside your store? You do so by actions and reducers (will be explained shortly).

State Is Read Only Example

store.dispatch({
type: 'COMPLETE_TODO',
index: 1
})
store.dispatch({
type: 'SET VISIBILITY FILTER',
filter: 'SHOW COMPLETED
})

Changes are made with Pure Functions

Pure functions are those functions that return the expected result based on the parameters. They’re purely synchronous not asynchronous. To make changes in our store we use these functions and we call them reducers. They don’t mutate existing state rather they create a new state tree.

Changes are made with Pure Functions Example

function visibilityFilter(state = 'SHOW_ALL',action) {
switch (action.type) {
case 'SET VISIBILITY FILTER':
return action.filter
default:
return state
}
}
function todos(state = (), action) {
switch (action.type) {
case 'ADD_TODO:
return [...state,
text: action.text,
completed: false
}
]
case 'COMPLETE TO DO:
return state.map((todo, index) => {
if (index === action.index) {
return Object.assign({}, todo,{
completed: true
})
}
return todo
})
default:
return state
}
}
import { combineReducers, createStore } from
'redux'
const reducer = combineReducer-
s({ visibilityFilter, todos })
const store = createStore(reducer)

This will Redux in your React application. Do you have ever think about why we would need Redux in our application? Let’s say we have a component called Main Component. And the Main Component has child Components. If the main component has to deliver states to its child components. They make a relationship tree that will deliver states. But If there are lots of components and they have a lot of child components. What you should do? Store rescue us from this problem. That distributes states between components. This is all about Redux! Now let’s go ahead and install Redux in our React application.

Installation of Redux

We can install Redux by the following command:
npm install redux --save

This will install Redux in our application.

Now go ahead into index.js  src/index.js
Import createStore from 'redux';

This will import createStore from Redux. Then we can create a new reducer also called functions:



To create a new reducer Example

const Reducer = (state, action) => {
switch (action.type) {
case 'ADD:
state = state + action.payload;
break;
case 'SUBTRACT:
state = state - action.payload;
break;
}
return state;
}

That Adds and Subtracts numbers. Then we will create a new store.

const store = createStore(Reducer,0)

We created a store with initial value O for the state to subtract and add. Then we can create a callback function that will run when a state is changed!

store.subscribe()=>{
console.log("Store Updated!",store.getState());
});

Then we can dispatch the functions to add a number or to subtract a number.

store.dispatch({
type: "ADD"
payload: 3
}) ;
store.dispatch({
type: "ADD",
payload: 1
});

Redux in React JS Example

Our final index.js file should Lookalike:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './app.js';
import bootstrap/dist/css/bootstrap.min.css';
import {createStore} from 'redux;
const Reducer = (state, action) => {
switch (action.type) {
case 'ADD:
state = state + action.payload;
break;
case 'SUBTRACT:
state = state - action.payload;
break;
}
return state;
}
const store createStore(Reducer,0);
store.subscribe(() = >console.log("Store Updated!",store.getState());
}) ;
store.dispatch({
type: "ADD",
payload: 3
});
store.dispatch({
type: "ADD",
payload: 1
});
store.dispatch({
type: "ADD",
payload: 2
});
ReactDOM.render(<App />,document.getElementById('root'));
ById('root'));

Redux in React JS Example Output

Now go to your web console and see this will print on your console:

Redux in React JS Example Output
This means our Redux application is working! Right. so Create we can create another example, A working example. We will create a button click increment example. If a user clicks on a button, the counter will increment the times the button is clicked. let’s create a folder called components and reducers under /src directory.

To create files with content Example

src/components/Counter.js


import React, { Component}from 'react
import Proptypes from 'prop-types
export default class Counter extends Component {
constructor(props) {
super(props);
this.incrementAsync = this.incrementAsync.bind(this);
this.increment = this.increment food.bind(this);
}
incrementIfOdd() {
if (this.props.value % 2 !== 0) {
this.props.onIncrement()
}
}
incrementAl sync() {
setTimeout(this.props.on Increment, 1000)
}
render() {
const { value, on Increment, and Decrement } =
this.props
return (
<p>
Clicked: {value} times
{"}
<button onClick={onIncrement}>
</button>
{"}
<button onClick={onDecrement}>
</button>
{"}
<button onClick={this.increment food}>
Increment if odd
</button>
{"}
<button onClick{this.increment Async}>
Increment async
</button>
</p>
)
}
}
Counter.propTypes = {
value: Proptypes.number.isRequired,
Increment: Proptypes.func.isRequired,
on Decrement: PropTypes.func.isRequired
}
src/reducers/index.js
export default (state 0, action) =>{
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT":
return state -1
default:
return state
}
}
src/index.js
import React from 'react'
import ReactDOM from 'react-dom'
import createStore } from redux'
import Counter from './components/Counter'
import counter from './reducers'
const store = createStore(counter)
const rootel = document.getElementById('root')
const render = () => ReactDOM.render
<Counter value={store.getState()}
OnIncrement={( => store.dispatch({ type:
INCREMENT' })}
Decrement={() store.dispatch(f type:"DECREMENT })}
/>,
rootEl
)
render()
store.subscribe(render)

To create files with content Example Output

This will give greet us with counterexample:

redux2

Now go ahead try clicking the button to see the magic!