DEV Community

loading...

Part 1: Redux?

Cicada0315
I have not failed. I've just found 10,000 ways that won't work. -Thomas Edison
Updated on ・4 min read

What is Redux?

Redux is a state container for JavaScript applications. It's basically another library. Redux puts all of our data(state) in one place. All the parts of Redux are plain old JavaScript including state(obj). You can use Redux together with React, or with any other view library. I will go over how Redux-React works in another blog but first let's learn about Redux.
How Redux-React works,
link: https://dev.to/cicada0315/part-2-redux-react-1lp

Why using Redux?

Redux state is separate from the component tree so, we can get any part of this data(state) for any component just by connecting the component.

Redux made complex interaction between components much easier. For example, there is one parent and from that parent there is two sibling components. If both of siblings displaying or manipulating the same data (state), the data needs to be stored in their parent component's state and passing props up and down to accessible for both siblings. Passing props up and down makes code complicated and messy. However, with Redux, every component we allow can get the update state data regardless of the their position of component tree.

alt Component tree Image_link: https://css-tricks.com/learning-react-redux/

Three Principles

Three principles comes from this link:
https://redux.js.org/understanding/thinking-in-redux/three-principles

1. Single source of truth

The global state of your application is stored in an object tree within a single store.

2. State is read-only

The only way to change the state is to emit an action, an object describing what happened.

3. Changes are made with pure functions

To specify how the state tree is transformed by actions, you write pure function reducers.

pure function: It returns the same result for same arguments, it does not alter input data, no modification of local and global variables and it does not depend on the external state like a global variable.

const addtwo = n => n+2;
Enter fullscreen mode Exit fullscreen mode

link: https://www.tutorialspoint.com/redux/redux_pure_functions.htm

Reducers: It's a pure functions that take the previous state and an action. It returns the next state without mutating the previous state. Simply, it only returns new state obj.

function reducer(state, action){ }
Enter fullscreen mode Exit fullscreen mode

More terminology to understand redux

store: It's a container that carry the whole state tree of your application. There should only be a single store in your app (use combineReducers to create a single root reducer out of many).
To change the state is through(dispatch) an action and this is the only way.

createStore() method: It is provided by the redux library. Creates and returns store as obj that will have a dispatch method and a getState(which returns the current state value) method.

createStore(reducer, [preloadedState], [enhancer])
Enter fullscreen mode Exit fullscreen mode

preloadedState (any): Optional parameter that can define the initial state.
enhancer (Function): Optional parameter that enhance the store.

dispatch function: Dispatches an action. This is the only way to trigger a state change.

dispatch(action)
dispatch({type: 'INCREASE_COUNT'})
Enter fullscreen mode Exit fullscreen mode

How redux works?

Note: Not actually using Redux yet just showing you how redux works(implementing redux not using redux library).
Redux dispatches action, dispatch evokes reducer and then with updated state it renders the view. The flows like down below image.

alt Data flow Diagram_link: https://redux.js.org/tutorials/fundamentals/part-2-concepts-data-flow

Let's sum up everything we discussed in one example code. I will implement a bank account which shows in DataFlowDiagram above:

Example code,

There is two buttons deposit $10 and withdraw $10, every time you click deposit $10 then the balance increase $10 on the other hands, whenever you click withdraw $10 then the balance decrease by $10.

//script.js
function createStore(reducder){
  let state;
  function dispatch(action){
    state=reducer(state, action);
    render();
  };
  function getState(){
    return state;
  };
  return {
    dispatch, getState
  };
};

function reducer(state ={
  balance: 0
}, action){
  switch (action.type) {
    case 'DEPOSIT':
      return {
        balance: state.balance+ action.payload
      };
    case 'WITHDRAW':
      return {
        balance: state.balance- action.payload
      };
     default:
      return state;
  };
};

function render(){
  const accountbalancetag=document.getElementById("output");
  accountbalancetag.innerText="Balance:" +store.getState().balance;
};

const handledeposit=(e)=>{
  store.dispatch({ type: 'DEPOSIT', payload:10 });
};

const handlewithdraw=(e)=>{
  store.dispatch({ type: 'WITHDRAW', payload:10 });
};

let store =createStore(reducer);
const depositbutton=document.getElementById("deposit");
depositbutton.addEventListener('click', handledeposit);
const withdrawbutton=document.getElementById("withdraw");
withdrawbutton.addEventListener('click', handlewithdraw);

//index.html
<div>
  <h1>Bank Account</h1>
  <h2 id="output">
  Balance: 0
  </h2>
  <button id="deposit">
    Deposit $10
  </button>
  <br />
  <button id="withdraw">
    Withdraw $10
  </button>
</div>
Enter fullscreen mode Exit fullscreen mode

If you want to see what is happening use this,
link: https://playcode.io/new/
Copy and paste code to the appropriate field to check what the app looks like. Whenever you modify the code then you have to wait 7sec but it's really good when you are doing quick check with complete code.

I hope this helps you to understand Redux.

Discussion (0)