So sánh redux thunk và redux saga
Redux saga là một thư viện giúp các side effect của ứng dụng tức là những thứ không đồng bộ như tìm nạp dữ liệu và những thứ không tinh khiết như truy cập bộ nhớ cache của trình duyệt dễ quản lý hơn, thực thi hiệu quả hơn, dễ kiểm tra và xử lý lỗi tốt hơn. Redux-saga là một phần mềm trung gian của redux (Redux là một thư viện JavaScript mã nguồn mở để quản lý trạng thái ứng dụng. Nó được sử dụng phổ biến nhất với các thư viện như React hoặc Angular để xây dựng giao diện người dùng). Phần mềm Redux này có thể được bắt đầu, tạm dừng và hủy khỏi ứng dụng chính với các hành động redux bình thường. Redux saga có quyền truy cập vào trạng thái ứng dụng redux đầy đủ và gửi các hành động Redux. Redux saga sử dụng một tính năng ES6 được gọi là Generators khiến các luồng không đồng bộ đó dễ đọc, ghi và kiểm tra. Bằng cách sử dụng Redux saga, các luồng không đồng bộ này trông giống như mã JavaScript đồng bộ tiêu chuẩn của bạn. Generator function là gì?Generator function là một function có khả năng tạm ngừng hoạt động trước khi hàm kết thúc. Đồng thời chúng có thể chạy lại tại một thời điểm yêu cầu khác. Tính năng này của Redux saga giúp ta giải quyết được các công việc một cách đồng bộ. Hàm sẽ dừng và đợi async chạy xong mới tiếp tục công việc của mình. Ví dụ: Để hiểu hơn về function này trong Redux saga, hãy tham khảo 1 ví dụ đơn giản dưới đây:
Việc gọi một hàm trình tạo không thực thi nó cùng một lúc; thay vào đó, Redux sẽ trả về một đối tượng trình lặp. Khi chúng ta gọi phương thức next trên đối tượng vòng lặp, thân hàm sẽ được thực thi cho đến khi nó nhìn thấy từ khóa “yield” tiếp theo. Phương thức next trả về một đối tượng có thuộc tính “value” có giá trị đã được trả về theo kết quả và thuộc tính “done” là viết tắt của việc một hàm đã hoàn thành việc thực thi hay chưa. Redux saga cung cấp cho người dùng một số method gọi là effect, cụ thể như sau:
Cài đặt Redux SagaĐể cài đặt Redux saga, bạn có thể thực hiện một trong 2 cách sau:
Hoặc
Ngoài ra, bạn có thể sử dụng các bản dựng UMD được cung cấp trực tiếp trong < script > thẻ của trang HTML. Khi nào nên sử dụng Redux saga?Sử dụng Redux saga sẽ thực sự có ích khi bạn muốn thực hiện một action mà không làm thay đổi trạng thái của ứng dụng
Redux saga hoạt động như thế nào?Redux dựa trên kiến trúc thông lượng và hỗ trợ luồng dữ liệu một chiều. Dữ liệu trong ứng dụng lặp đi lặp lại cùng một vòng tuần hoàn, giúp cho mọi thứ diễn ra trong trạng thái dễ dự đoán hơn. Ưu, nhược điểm của Redux SagaSử dụng Redux Saga để quản lý các side effect của ứng dụng mang đến cho người sử dụng nhiều trải nghiệm mới thú vị. Tuy nhiên, Redux Saga cũng có một số ưu, nhược điểm. Cụ thể sẽ được liệt kê dưới đây: Ưu điểm
Nhược điểm
So sánh Redux saga và Redux thunkTrong quá trình hoàn thành các dự án, Redux saga và Redux thunk luôn là 2 công cụ hữu ích đối với các nhà phát triển phần mềm. Tuy nhiên, bạn đã bao giờ thử đặt lên bàn cân 2 công cụ này để so sánh chúng? Hãy để GrowUpWork làm việc này trong bài viết này nhé!
Redux Saga theo dõi các hành động đã gửi và kích hoạt lệnh gọi API hoặc bất kỳ tác dụng phụ nào khác mà bạn viết code. Saga hoạt động giống như một chuỗi riêng biệt hoặc một quy trình nền hoàn toàn chịu trách nhiệm về việc thực hiện các tác dụng phụ hoặc lệnh gọi API của bạn. Điều này khác hoàn toàn với redux thunk. Redux thunk sử dụng lệnh gọi lại có thể dẫn đến các tình huống khó khăn' trong một số trường hợp. Với các dự án quy mô vừa và nhỏ, Redux thunk có thể sẽ hữu ích hơn bởi nó hoạt động khá đơn giản. Tuy nhiên với các dự án lớn hơn, Redux thunk sẽ khiến bạn gặp phải nhiều rắc rối bởi nó khó có thể mở rộng nếu hiệu ứng phụ hoặc logic không đồng bộ của bạn tăng lên. Đây là lúc Redux saga trở nên vô cùng hữu ích và có sức mạnh tuyệt vời. Chúng cung cấp các công cụ tạo hiệu ứng đồng thời, hủy bỏ tác dụng phụ và dễ mở rộng hiệu ứng trên cơ sở các quy mô lớn hơn. Kết luậnHi vọng qua bài viết này đã các bạn đã có được những thông tin cơ bản về Redux saga dành cho người mới bắt đầu. Hãy theo dõi GrowUpWork để cập nhập thêm nhiều bài viết về các công cụ xử lý dữ liệu hữu ích khác nhé!
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.
Why Redux?
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. Isn’t this amazing?
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.
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: |