Principles of Redux
Single Source Of Truth
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
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
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
npm install redux --save
This will install Redux in our application.
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:
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:
Now go ahead try clicking the button to see the magic!