React : The Redux Way đ
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,
- Step by Step Guide To Building React Redux App
- Using Middlewareâs In React Redux Apps
- Adding A Robust Form Validation To React Redux Apps
- The Anatomy Of A React Redux App
- Why Redux Need Reducers To Be âPure Functionsâ
- Two Quick Ways To Reduce React Appâs Size In Production
- ReactJs library by Facebook
- 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 đ¨âđť đ.