Build Your Own redux from scratch
Tags: react, redux, javascript, webdev
Published: 2018-07-07 13:35:50

---
title: Build Your Own redux from scratch
published: true
description: Build Your Own redux from scratch
tags: react,redux,javascript,webdev
cover_image: https://cdn.pixabay.com/photo/2015/12/07/10/58/building-1080592_960_720.jpg
---

**Redux is a State Mangement library for React apps as it helps to manage the app state in a single Object it means the whole app state lives on a single Object.**

If you try to connect a redux store you have to do some boilerplate setup to your react app often sometimes confusing.

So that's why we write it from scratch.


Create a store.js file in your react app.

first, we need to create a dispatch function, subscribe function, thunk function

{% gist https://gist.github.com/saigowthamr/518a66690646b59d776260cb820d26d0 %}

1.getState function helps to get the app current state.
2.thunk is used to do aysnc things you can even delay the network request.


create a reducers.js file
 {% gist https://gist.github.com/saigowthamr/52f707d08c06a744cbf3df93e9b4c67e %}

#### Reducer

when we dispatch an action it gives the new app state instead of mutating the old state.

### How to connect our redux to the React app?

open your index.js file and import subscribe from the store that's it you are connected to the store like how i did in below code.

```javascript
import React from "react";
import { render } from "react-dom";
import "./index.css";
import App from "./App";
import { subscribe } from './store';

subscribe(()=>render(
  <App />,
  document.getElementById("root")
))
```

Now let's implement a counter and todo, and send some network requests so that we can know our redux is working correctly or not.

todo.js file

{% gist https://gist.github.com/saigowthamr/b923a643d6e9e674f810871a69c8a6e5 %}

in above code first, we imported getState and dispatch from the store.

when we click an add todo button we are dispatching the type of the action with a payload,getState helps to get the added todos from the store.

**counterbuttons.js file**

```javascript
import React from "react";
import {dispatch} from './store'

function Inc() {
    dispatch({
        type: 'INC'
    })
}
function Dec() {
    dispatch({
        type: 'DEC'
    })
}

const width = { width: '2rem' ,fontSize:'1.2rem'}

const CounterButtons= () => (
  <div>
    <button onClick={Inc} style={width} >+</button>
    <button onClick={Dec}  style={width} >-</button>
  </div>
);

export default CounterButtons;
```

It's time to send a network requests using thunks and thunks are used to make a network requests.

create a **thunks.js** file

```javascript
import { dispatch, thunk } from "./store";
import axios from "axios";

export const users = () => thunk(
    function (res) {
        dispatch({
            type: "GET_USERS",
            users: res.data
        });
    }, (cb) => {
        axios.get('https://jsonplaceholder.typicode.com/users')
            .then(response => cb(response)) 
            .catch(err => cb({ err:'Error occurred'}))
    },5000 //delay time
)
```
thunk function takes the three arguments first two are callback functions last
argument is delay and it is optional.

in the first callback function, you need to invoke the dispatch with the type of action and payload


in second callback you need to make a network request whenever response comes back wrap with cb(callback) function. so that you can take the response from the first call back function parameter.

**FetchData Component**
```javascript
import React from "react";
import { getState } from "./store";
import { users } from "./thunks";

function Loading() {
  return <h1 style={{ color: "red" }}>Loading</h1>;
}

class FetchData extends React.Component {
  componentDidMount() {
    users();
  }
  Users = () => {
    if (getState().users) {
      return getState().users.map(user => (
        <ul key={user.id}>
          <li>{user.name}</li>
          <li>{user.email}</li>
        </ul>
      ));
    } else {
      return <h1 style={{color:'red'}}>Delaying request for 5seconds</h1>;
    }
  };

  render() {
    return (
      <div>
        <ul>
          <li>{getState().data ? getState().data : <Loading />}</li>
        </ul>

        <hr />
        <h1>Users</h1>
        <hr />

        {this.Users()}
      </div>
    );
  }
}

export default FetchData;
```

that's it we are done with creating all components.

Now we need to import these components in App.js file because our app doesn't aware of these components.

App.js file
{% gist https://gist.github.com/saigowthamr/55a8097cffca4b1ff872df6282dbe4d9 %}

Hoo successfully completed 

final output

![](https://raw.githubusercontent.com/saigowthamr/React-Store/master/screenshot.gif)


Hope you guys enjoyed...👍🏻
### [Code Repository](https://github.com/saigowthamr/React-Store)