React : The Redux Way 😇

Yuvraj Pandey
MindOrks
Published in
6 min readAug 24, 2018

Well if you are well versed with Web development or have some know how of it , then definitely you must have come across the term “React”. Lets start with some introduction to React first so that even the new learner’s feel comfortable with the term.

What is React ?

React is a JavaScript library created by Facebook for building seamless user interfaces. Design simple views for each state in your application, and React will efficiently update and render i.e display just the right components when your data changes, thereby making your code more predictable, simpler to understand, and easier to debug. React enables us to build complex components that manage their own state which then compose them to make complex user interface.

Component logic is written in JavaScript instead of templates, you can easily pass rich data through your app and keep state out of the DOM.

What is Redux ?

Redux takes away some of the hassles faced with state management in large applications. It provides you with a great developer experience, and makes sure that the testability of your app isn’t sacrificed for any of those.

As you develop React applications, you may find that keeping all your state in a top-level component is no longer sufficient for you. You may also have a lot of data changing in your application over time.Redux helps solve these kinds of problems. Mind you, it isn’t the only solution out there.

If you’ve spent some time doing a bit of research, then you’ve come across them already. There’s Redux, React-Redux, Redux-thunk, Redux-saga, Redux-promise, Reselect, Recompose and many more!

As if that’s not enough, there’s also some Routing, Authentication, Server side rendering, Testing, and Bundling sprinkled on it — all at once.

Gosh! That is overwhelming.

But Why Redux 😅 ?

The real problem with Redux is — especially for beginners — isn’t the complexity of the Redux library itself. No. I don’t think that is it. It is just a tiny 2kb library — including dependencies.

Take a look at the Redux community as a beginner, and you’re going to lose your mind fast. There’s not just Redux, but a whole lot of other supposed “associated libraries” needed to build real world apps.

For example, in larger apps with a lot of moving pieces, state management becomes a huge concern. Redux ticks that off quite well without performance concerns or trading off testability.

One other reason a lot of developers love Redux is the developer experience that comes with it. A lot of other tools have begun to do similar things, but big credits to Redux.

Some of the nice things you get with using Redux include logging, hot reloading, time travel, universal apps, record and replay — all without doing so much on your end as the developer. These things will likely sound fancy until you use them and see for yourself.

React — A JS library that helps us to divide up our app into multiple components but doesn’t clearly specify how to keep track of the data(i.e its State) and how to deal with all the events(i.e Actions) properly.

Redux — A complimentary library to React that provides a way to easily keep the data(State) and the events(Actions) intact throughout the product lifecycle. We just need to decide which data’s state needs to me maintained and Redux will provide you with all feasibility to do so.

Lets Begin

Actions

They are payloads or simply plain JavaScript objects of information that send data from your application to your store thereby acting as a source of information for the store.

Here’s an example of Action :

const ADD_POST = 'ADD_POST'{   type: ADD_POST,   text: 'My Post'}

Actions must always have a type property that indicates the type of action being performed so as to differentiate from the other types of Action that you would define once the application grows huge. Types should typically be defined as string constants.

export const getPosts = () => dispatch => {  fetch('https://jsonplaceholder.typicode.com/posts')     .then(res => res.json())     .then(data => dispatch({        type : GET_POSTS,        posts : data  }))}

Consider a sample action as above in which we initiate an API call for fetching some dummy post. Also if u see on response we create a dispatch in which we pass an action object containing type & posts property.

Note : dispatch in redux is similar to promise in javascript which can be used to create asynchronous applications.

Reducers

So once you have fired the Action for the application we need some mechanism that would react to those action’s & respond’s with some state i.e data. Remember that actions only describe what just happened, but don’t describe how the application’s state changes considering those action.

Now that we’ve decided what our Action object looks like, we’re ready to write a reducer for it. The reducer is a pure function that takes the previous state and an action, and returns the next state.

const initialState = {   items : [],   item : {}}function postReducer(state = initialState, action){   switch(action.type){       case GET_POSTS:            return {               ...state,               items : action.posts             }       default:            return state;   }}export default combineReducers({    posts: postReducer});

As you can observe function postReducer(state = initialState, action) accepts an old i.e initial state & action that we created in our previous example response of API. The combineReducers function in redux can be used to combine multiple reducer’s logic for more complex computation logic.

Store

The Store is the object in Redux that brings all the Action’s & Reducer’s together under one container. Store basically holds the application state and maintain’s it throughout the application lifecycle. We can easily get the access to the current state of the Store using getState() function.

console.log(store.getState())

Also we can update the state at any time using dispatch(action) as follows,

store.dispatch(addPost({
type : "NEW_POST"
text : "Post"}))

We create a store by using a simple function in redux i.e createStore. So either you can maintain a separate Store file or you can create its instance in any component as per required.

import { createStore } from 'redux'import postReducers from './reducers'const store = createStore(postReducers)

For more information you can check out the following resources which can guide you with more fundamental’s of React with Redux,

  1. Step by Step Guide To Building React Redux App
  2. Using Middleware’s In React Redux Apps
  3. Adding A Robust Form Validation To React Redux Apps
  4. The Anatomy Of A React Redux App
  5. Why Redux Need Reducers To Be “Pure Functions”
  6. Two Quick Ways To Reduce React App’s Size In Production
  7. ReactJs library by Facebook
  8. Redux Library

That’s it for this article hope you would have learn something useful from it. So If you have any thoughts or suggestions, feel free to leave a comment below. Don’t forget to share your love by clapping for this article as many times you feel like.

You can follow me on Twitter , Github , LinkedIn , Facebook.

Happy Coding 👨‍💻 🎊.

--

--

Yuvraj Pandey
MindOrks
Writer for

Working towards striking an impact using technology for making this world a better place to live in âœ