I am very new to this redux.developed a project in flux now thought of upgrading it .I have used many API calls to get the data and used stores to get and retrieve data.
Can any one suggest me to use the right one either thunk or saga
In some blogs it was written to use MobX too.
I think the choice between the two depends on the product requirements. For simple UIs where there is simple data flow from a server response to react component, then just using thunk should suffice. For more complicated async interactions (where there needs to be coordination between react components), sagas can help out quite a bit by providing structure to your code. There is some amount of learning curve with sagas so you might want to start very small and make sure you have plenty of test coverage for all your assumptions. Redux Saga Test Plan is great at helping you test your sagas.
For my current project, we started with thunk then transitioned to saga because our use cases were complex enough to leverage the benefit of sagas.
I have not used MobX so I can't comment on that.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 months ago.
Improve this question
Looks like thunk and saga are 2 types of middleware to allow side effects and asyncronous actions in Redux Toolkit. Based on some basic googling, looks like thunk and saga basically serve the same purpose. Without understanding the key differences between the 2 types of middleware and based on some basic googling, I get the impression that historically, thunk has generally been preferred for small to medium size apps whereas saga has generally been preferred for larger apps.
However, Redux Toolkit has included thunk as default middleware for its slice implementation. So it seems like the Redux Toolkit dev team has decided that thunk is a better choice than saga. Am I inferring this rationale correctly? Can you think of a scenario where saga would be a better choice than thunk for a Redux Toolkit implementation (outside of bias based on the level of developer experience with sagas in particular)? Or does the inclusion of thunk as the default indicate that the Redux Toolkit dev team has chosen thunk as the winner between those 2 middleware technologies?
Looks like createAsyncThunk is the main function used with thunks and it's generally used in regards to supporting api integration. Taking a step back, the general purpose of thunk is to "allow side effects and asyncronous actions" but in reality, is the vast majority of thunk implementations in production apps used to specifically support api integration? For example, if I stated in an interview that I had only used thunks for api integration then would that be a reasonable statement if that's the 90%+ use case for thunk usage? Or are there any specific scenarios where you've used thunks in the past which were not specifically for api integration but represent an important use case scenario that you think developers should understand?
Finally, looks like the Redux Toolkit dev team recommends RTK Query for API integration as opposed to thunks these days. So what would you see as the main scenarios, if any, where using thunks would be the recommended approach in a new Redux Toolkit implementation?
I'm a Redux maintainer and creator of Redux Toolkit.
The short answer to all of the above is "yep!".
Thunks have always been the default / most common side effect middleware for Redux apps, largely because of their simplicity. That's why RTK includes support for thunks out of the box. it's also worth noting that while "fetch data and dispatch actions based on the result" is probably the most common thunk use case, thunks may contain any logic, sync or async.
That said, it's true that the majority of "async logic" in most apps is really "fetch this data from an API". That's why we created RTK Query, which completely replaces the need to write any thunks, reducers, effects, or hooks to manage data fetching.
We've been generally recommending against use of sagas in most cases for years. Sagas are a great power tool, but they're kind of like a chainsaw. There are a few very specific occasions when you actually need that tool, and when you do, you need all the power. But it's not something you need on a daily basis, and we've been especially recommending against the use of sagas for data fetching use cases.
This is even more true now that RTK Query exists. Additionally, the new RTK "listener" middleware solves the same "reactive logic" use case as sagas, but with a simpler API, smaller bundle size, and better TS support.
Given that, there's almost no reason to use sagas today.
I'll paste the last slide from my "Evolution of Async Logic" talk:
What use case are you trying to solve?
Data Fetching
Use RTK Query as the default approach for data fetching and caching
If RTKQ doesn't fully fit for some reason, use createAsyncThunk
Only fall back to handwritten thunks if nothing else works
Don't use sagas or observables for data fetching!
Reacting to Actions / State Changes, Async Workflows
Use RTK listeners as the default for responding to store updates and writing long-running async workflows
Only use sagas / observables if listeners don't solve your use case well enough
Logic with State Access
Use thunks for complex sync and moderate async logic, including access to getState and dispatching multiple actions
I'd recommend reading through these additional articles, talks, and docs pages I've written:
Reactathon 2022: The Evolution of Redux Async Logic
Why Redux Toolkit Uses Thunks for Async Logic
Thoughts on Thunks, Sagas, Abstraction, and Reusability (2017)
Using Redux: Writing Logic with Thunks
"Redux Essentials", Part 7: RTK Query Basics
I am planning to build a large React application which might contain hundreds of components. But not sure what state management system to use between Redux and Context API.
Context API is in-built in React and doesn't need any third party library. It is easy to implement and solves the problem of sharing states at different levels of the component.
But on the other hand Redux is the Industry standard and has support for middleware to perform async actions.
If I choose Context API how can we manage API calls with it. Also do you think it is a good idea to use context for a large application where we might need state objects extensively.
The design benefit from Redux is that the action does not implement. An action is an indication that something happened (for example SAVE_PROFILE_CLICKED) but the action doesn't do anything (like connecting to api, sending data and saving response in state). You can do this with context api but the separation isn't enforced as much and you won't have the redux devtools. The pattern is called event store/sourcing. You could change the reducer and replay the events to see if your changes work and create a consistent state, testing is easier, extending is easier, logic is better isolated and probably many more benefits to be had.
The design also separates writing to state (reducer), side effects (thunk) and reading from it (selectors). This pattern (writing/reading separation) is called cqrs. Your query/selector is separated from the command/reducer. This gives you easier testing, isolation of logic, less chance of duplicate implementation and probably many more benefits.
You can still make a complete mess of your project when using Redux and not fully understand it so using Redux does not guarantee anything.
If I choose Context API how can we manage API calls with it.
You can do it any way you like it, the question is too general to answer.
Also do you think it is a good idea to use context for a large application where we might need state objects extensively.
As stated before; Redux is no guarantee your project won't be a mess. It will give you the tools to implement certain patterns with more ease. Make sure you understand it and it's patterns. Most example applications don't demonstrate why Redux is so powerful as the problem they implement (counter, todo app) isn't complex enough to even warrant using it. I can only advice you would write code that you're comfortable with and can understand.
I am using Apollo Client 3.0 to fetch data from graphql server, but I can't decide what to use for local state management (Redux or Apollo Client 3.0).
I think Redux force me to write more code, but in a predictable and cleaner way which it's good. Also adding Redux to the app means I will have mix of 2 state management libraries.
Apollo Client 3.0 has Reactive Variables, but for large application I think it will become a mess! Also I can use queries and mutations with #client directive, but this could be a little bit confusing.
What do you recommend me ?
What should I use ?
Can you provide me some good examples ?
Thanks!
Apollo is not a state management library. It's an amazing client & cache for graphql, but when you start using it as a client-side state management, you'll notice that it isn't really meant for that.
The amount of code you have to write is similar to vanilla redux, as you have to write your own resolvers for every local query and mutation, but since there is a text-based protocol in-between, you lose all type safety you could have when staying "pure JavaScript". And then you have to manually put your data into a normalized cache, even if your data is not normalized, so you'll start putting your settings into settings/1, because everything needs an id, even if you have only one instance of settings in your application.
It all feels very clumsy from my experience.
Also, modern redux has a lot less boilerplate than you might be used to right now - if you follow the official recommendation to use redux toolkit (take a look at this page of the official redux docs), you'll write probably a fourth of code code you are used to with "vanilla redux".
Modern redux doesn't have hand-written action creators, action types, switch-case reducers or immutable logic. Those are all implementation details that are handled under the hood by now.
I actually did a conference talk on the topic a year and half ago, so I have some examples.
Here is what you write with Apollo (and yeah, the example is a bit artificial for Apollo - but I wanted to use the same example for all libraries and a login flow was what I had gone for)
This is what it looks like in redux
Im using Context API for multi store management and React-Redux with thunk for a single store management.
Should I stick to one over the other or should I use React-Redux for multiple store management over React's Context API.
I spoke with a friend who did vice-versa versus me for his company and im wondering why but never got an explanation.
Whats the best practice?
React Context API is somewhat harder to manage you can use redux instead to manage states.
react-redux is just used as a connector between react and redux.
You can do the following for best practices:
For multi store management you can go for redux.
For connecting react with redux you can go for react-redux.
For middle ware you can either go for redux-thunk or redux-saga.
I prefer redux-saga as it has more advantages over redux-thunk.
Redux was and still is very popular for large applications where you need to be able to maintain a single source of truth but pass down different parts of the store as props to various components. The advantage of this package is that it can make debugging easier and if implemented correctly is very robust.
As far as redux middleware goes, they are generally used for asynchronous integration. Thunk and Saga are two popular libraries. Context should be able to handle async without any other dependencies.
Context API is a newer feature released as part of React 16.3 and allows for easier store creation but, in my opinion, can be more difficult to scale. I don't have as much experience using Context API but it has become very popular and for an experienced developer can do anything redux does.
I would say it is generally discouraged to use both when one approach would work just as well. That being said, an application I manage uses both, because when it was first created Context API 16.3 had not yet been released so redux was the only state manager for the whole app, but later some localized component states were updated to have their own context store. I don't think this is the best practice, however.
Read more about the technical differences here.
One of the best and most overlooked alternatives to Redux is to use React's own built-in Context API.
Context API provides a different approach to tackling the data flow problem between React’s deeply nested components. Context has been around with React for quite a while, but it has changed significantly since its inception. Up to version 16.3, it was a way to handle the state data outside the React component tree. It was an experimental feature not recommended for most use cases.
Initially, the problem with legacy context was that updates to values that were passed down with context could be “blocked” if a component skipped rendering through the shouldComponentUpdate lifecycle method. Since many components relied on shouldComponentUpdate for performance optimizations, the legacy context was useless for passing down plain data.
The new version of Context API is a dependency injection mechanism that allows passing data through the component tree without having to pass props down manually at every level.
The most important thing here is that, unlike Redux, Context API is not a state management system. Instead, it’s a dependency injection mechanism where you manage a state in a React component. We get a state management system when using it with useContext and useReducer hooks.
If an application isn't overly complex, it is highly preferable to use the built-in Content API over adding another library that adds unnecessary complexity. Remember - most states do not need to be global.
A great next step to learning more is to read this article by Andy Fernandez: https://www.scalablepath.com/react/context-api-vs-redux
Are Relay and Redux alternatives to each other? When are they best used with? Can we use Relay, GraphQL with Redux?
REDUX:
Redux is library
Redux is a state container for your app
Its a single point source where all information related to your app is stored.
You create actions,reducers and update your state by dispatching actions.
The state is immutable and you cannot update it. Always a cloned version of state is returned.
You use packages like redux-thunk / redux-saga to call apis. On Response of API's you update your state.
Now if you see in redux there is a lot of boilerplate code.
I personally find redux really cool and handy but you need to take care of following:-
Creating actions/reducers/store.
Dispatching actions and updating store.
Handling api calls.
Implement caching.
Maintaining store.
Maintaining expected props in components.
RELAY:
Relay is a Javascript Framework.
Handles store for you. You dont have to worry about updating store
Takes care of your API calls(this is the best feature)
Store is immutable and clone version is returned.
Works with GraphQL(this part is bit tricky as you need to understand graphql as well). After working on this for sometime I realised this is one major drawback. But once you understand graphql its really powerful
Works on queries and mutations
Relay is really really powerful and provides following benefits:-
You dont need to work about API calls. Relay network layer takes care of it. You do that through specifying queries and mutations
One of the best features of relay which makes it really useful is caching implementation. It reduces api calls drastically.
Relay is really really powerful but you there is bit of overhead when you get started. Following are the pre-requisites:-
React
Graphql
ES2015 JS
Once you are done with prerequisites also understanding how relay actually works is bit tricky and not as easy as redux. But once you understand how it works and why was it brought into picture you would really be amazed. Its indeed a really powerful tool.
So in case of your project is small-medium sized I would say go with redux and if its on large scale relay. But if you are working on react-native do give relay a try , its really interesting.
Also,yes you can use redux with relay.