DEV Community

loading...
Cover image for Build Your Own redux from scratch

Build Your Own redux from scratch

sait profile image Sai gowtham ・3 min read

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

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

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.

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")
))
Enter fullscreen mode Exit fullscreen mode

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

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

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;
Enter fullscreen mode Exit fullscreen mode

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

create a thunks.js file

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
)
Enter fullscreen mode Exit fullscreen mode

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

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;
Enter fullscreen mode Exit fullscreen mode

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

Hoo successfully completed

final output

Hope you guys enjoyed...👍🏻

Code Repository

Discussion (6)

pic
Editor guide
Collapse
ivanoung profile image
Ivan Oung

That's pretty cool, thanks!

Collapse
sait profile image
Sai gowtham Author

it's my pleasure Ivan

Collapse
aditya81070 profile image
Aditya Agarwal

Are you following Udacity React nanodegree. This code seems very very familiar to me: :)

Collapse
sait profile image
Collapse
aditya81070 profile image
Aditya Agarwal

then what tutorials you are following?

Collapse
chadsteele profile image
Chad Steele

Great article! Thanks!
I think you'll like this alt to redux as well.
dev.to/chadsteele/eventmanager-an-...