Managing UI state within complex web applications of present times is difficult. In this blog, we will try to find out how we can manage UI states using Redux and what can be the most suitable middleware along with Redux for your next amazing project.
Passing or sharing data from one component to other is a major task and can sometimes be very frustrating. To help us with situations like these, Redux offers immense help. Redux keeps a single store (sometimes called as the ‘Single source of truth’ of all your application state(data) and the components can connect to the redux store and get back the data they want.
Redux follows a unidirectional data flow. Redux has 3 major components: ‘actions’, ‘reducers’ and the ‘store’.
Actions are simple JavaScript objects. It has a ‘type’ property which specifies the type of the action we are performing and optionally, can also have a ‘payload’ property which is used to send some data to our redux store.
A simple action object can be as follows:
Reducers are the functions that determine the changes in application state and return the updated state. They take actions as the argument and update the state inside the store.
Sample reducer will look like this:
Now that we have a basic understanding of Redux, let us now move on to see how we can make API calls using redux middleware libraries like Redux Thunk and Redux Saga.
Redux middleware is a function or a piece of code that sits between action and reducer and can interact with the dispatched action before reaching the reducer function.
A redux middleware can be used for many purposes such as logging (e.g. redux-logger), asynchronous API calls and so on.
Image: Redux Thunk vs Redux Saga
Redux and stuff is fine. What is “Thunk” anyway?
The word “Thunk” may seem vague at first but to put in amazingly simple terms, Thunk is just a function returned from another function.
Let us see an example:
Redux Thunk is a middleware that allows you to call the action creators that return a function(thunk) which takes the store’s dispatch method as the argument and which is afterwards used to dispatch the synchronous action after the API or side effects has been finished.
Confused? 😧😧😧 Let us see an example:
In the above example, getCartItems() is an action creator which returns a function which in turn takes dispatch method as the argument. After we have received the cartItems from the server, we will dispatch a regular synchronous action using the dispatch method.
I hope this makes sense now.
Now that we have seen what Redux Thunk helps us with, let us now see what Redux Saga offers us.
Redux Saga is also a middleware library that helps us with API calls or side effects. Redux Saga uses an ES6 feature called ‘Generators’ which helps us to write asynchronous code.
Generators are the functions that came with ECMA Script 6. And the amazing part is that the generator functions can be paused in between the execution or even can be exited and later re-entered.
A generator function is represented as: function* functionName() {}
Do not Sweat😰. This is not a Pointer.
A simple example of generator function can be:
Calling a generator function does not execute it at once; instead, it returns an iterator object. When we call the next() method on iterator object, function body is executed until it sees the next “yield” keyword.
next() method returns an object with a “value” property which has the value that has been returned by yield and a “done” property which stands for whether a function has completed execution or not.
Redux Saga listens to the dispatched actions and triggers an API call or any other side effect you write.
Let us see in an example for how we can call an API endpoint using Redux Saga.
Saga works like a separate thread or a background process that is solely responsible for making your side effects or API calls unlike redux-thunk, which uses callbacks which may lead to situations like ‘callback hell’ in some cases. However, with the async/await system, this problem can be minimized in redux-thunk.
It is completely up to you to choose the right approach for your projects. Personally, I have used both Redux-Thunk and Redux-Saga, and I feel if you are working on a small or a medium scale project, you can choose Redux-Thunk. It will work like a charm. But on the other hand, for bigger projects, Redux-Thunk may sometimes get you in trouble, as it can be hard to scale if your side effect or asynchronous logic increases, whereas in case of Redux-Saga, it comes power packed with some amazing things such as concurrent side effects, cancelling side effects, debouncing and is easy to scale.
To be honest, I love both tools. Choosing one is difficult as both have its advantages and disadvantages.
Redux-Thunk | Redux-Saga |
---|---|
Less boilerplate code | More boilerplate code |
Easy to understand as compared to redux-saga | Difficult to understand as there are multiple concepts to learn like generator functions and redux-saga effects |
May be difficult to scale up | Easy to scale as compared to redux-thunk |
Action creators may hold too much async logic | Action creators stay pure |
May get difficult to test | Comparatively easy to test as all your async logic remains together |
I hope this blog helps you choosing the suitable tool for your upcoming projects.
Happy Coding🥂
To know more about these libraries/tools, you can refer:
Written by Vishal Marhatta, System Executive at Eternus Solutions
17 Comments
I am incessantly thought about this, thanks for posting.
I am incessantly thought about this, thanks for posting.
Thank you for the helpful info! I would not have discovered this myself!
Thank you for your valuable information. Could you please provide an understandable example for react native login form/screen with Axios and Redux( redux-thunk , redux-logger , redux-persist). Waiting for your example : )
Why visitors still make use of to read news papers when in this technological globe everything is existing on net?
Very good blog!
I simply could not depart your web site prior to suggesting that I actually enjoyed the usual information a person supply for your visitors?
Is gonna be back ceaselessly in order to inspect new posts
Post writing is also a fun, if you be acquainted with after that you can write if not it is difficult to write.
If some one wishes expert view concerning running
a blog after that i suggest him/her to go to see this blog, Keep up the fastidious work.
Thanks for your good posting!
Somebody essentially lend a hand to make significantly posts I’d state.
This is the first time I frequented your website page and up to now?
I amazed with the research you made to create this actual publish extraordinary.
Fantastic job!
Thank you for your valuable information
I love reading an article that can make men and women think.
Also, many thanks for permitting me to comment!
I’m not certain where you’re getting your information, however
good topic. I must spend a while learning much more or understanding
more. Thanks for great info I was searching for this information for
my mission.
What’s up to every body, it’s my first pay a quick visit of
this web site; this website contains amazing and in fact fine stuff designed for visitors.
That was very helpful!!
However I do see hybrid sites that are mini-sites or full scale eCommerce sites, with AdSense at the bottom of their pages. This might not be so bad since only 1 – 15 of your site visitors will either buy from you or fill out a form.