Redux and ALL the application state - reactjs

in the Redux documentation is written:
In Redux, all the application state is stored as a single object.
And that starts my problem.
I'm writing an application that will manage few entities with many data in a SPA (React + Redux) and something is concerning me in to using Redux and get some kind of lag because the quantity of data that I'll need to manage.
I don't believe that transferring all the application state over Redux would be nice, because in some way, it may consume a lot of memory, but I may be wrong.
Redux looks like (to me) so simple and so confuse at the same time and I don't if I should or shouldn't use this, but, the application will grown a lot and I have sure that it will help me to maintain the project organized as well.
Another thing that scared me is about rendering DOM element when an updated state occur. It's different from using setState() on React and as we can see in the Redux videos from Dan Abramov, he is using a forceUpdate wich isn't recommended in the React docs.
Is it possible to manage the entities in different stores but put them together just when it is necessary?
Will it consume a lot of memory if storing all the application state in a single store object?
What's the best way to render React components using Redux?

You've definitely got several different questions there, and you are over-thinking things :)
First, caching data on the client-side is no different in Redux than with any other Javascript framework. In fact, caching data with Redux will likely take up less memory than it would with something like Backbone, because a Redux app will store plain JS objects and arrays rather than wrapping the data in model class instances. There's also no difference size-wise between splitting that data between multiple stores, and combining it all into a single state tree in one store.
Now, how much data you cache is up to you, but realistically you could easily load tens of thousands of records into a client app over time without having issues.
Second, don't confuse the small examples that Dan shows in those videos with how the React-Redux library really works. Dan was trying to illustrate some basic ideas, not show production-grade code. If it helps, he actually wrote a miniature version of connect that shows the basic idea of what connect actually does. Meanwhile, the real React-Redux library is highly optimized (and does actually use setState internally once it knows the data has really changed).
Finally, while you can create multiple stores, the Redux FAQ advises to only use one store, for several reasons.
I recently published a presentation that introduces the basics of React and Redux. You might want to read through that. I'd also encourage you to read through the Redux docs thoroughly.
Also, I keep a big list of links to high-quality tutorials and articles on React, Redux, and related topics, at https://github.com/markerikson/react-redux-links . Specifically intended to be a great starting point for anyone trying to learn the ecosystem, as well as a solid source of good info on more advanced topics.

Related

Is React Context API suitable for large scale applications

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.

Is it worth using Redux with a Meteor / React app?

I've used Meteor a fair bit and love it, the publish/subscribe model, the way the whole framework is thought out, the ease of writing the server-side code...and I've used React with Meteor, and that's also cool.
However I've recently done a non-Meteor project in React/Redux and there's a lot to love about Redux. It's more effort to set up but the single point Store and all the associated tools/systems are very nice.
My web app will do a lot of database interaction and needs optimistic UI.
So I'm wondering whether to use Meteor/React/Redux for my next project, especially as there are some limitations in MiniMongo (e.g. no support for arrays). However I'm not finding a lot of relevant tutorials on how to hook them together, for example this one is nearly 3 years old now. This makes me doubt whether many people are using this setup, and whether I'll be able to get it working easily: I know from past experience that I need step by step tutorials to get past the initial hurdles with a new setup, then after that I can work things out for myself.
I'll use Meteor/Redux next for sure. I know them, I like them. The question is whether adding Redux is worth the overhead? I hope this is a suitable question for StackOverflow, if not I will try posting it elsewhere.
I'd like to hear reasons to use or not use Redux with Meteor/React, and any recommendations for tutorials. Thank you.
I think Redux is applicable in the non-meteor world, although there are alternatives now with graphql local state or the use of the React context api (which, thanks to React Hooks, is no longer deprecated)
Anyway, back to the story...
I have two separate Meteor apps, one that uses Redux, and the other that doesn't.
Redux works well with Meteor, it does the async thing quite well, but it adds a whole lot of complexity for arguable benefit. In a non-meteor app where you are doing much more in the way of orchestrating asynchronous API calls, then it makes total sense, because you can effectively decouple the data handling from the UI.
But in a typical Meteor app, use of publications and subscriptions means that the data flows naturally anyway. A UI button requests a back end action. The Meteor method does the work, and updates the database, and that data is updated in the UI automatically.
Let's take a scenario that I implemented recently. Members of my app need a Working With Children Check. They are issued a number, and when we are processing membershio renewals, we need to check that the number is still valid. This is initiated by a button on the UI, which calls a Meteor method, which in turn does an API call. The method simply updates the results of the check (even if it fails) into the member's database record. A return value from the Meteor call allows us to do a toast notificaton for the user, and pub/sub looks after updating the new status in the UI.
This could also be done with Redux, but pretty much all of the above code needs to be done anyway.
My preference is away from Redux, as there are alternatives, and it feels like it is a level of engineering that takes you away from writing your app.

Using redux with a local database

I have an offline React web app where all data is stored locally in indexedDB. There is no server other than the file hosting for static assets. I am getting to the point where I am starting to look into using redux now but I am trying to understand the tradeoffs between moving more data into the store and continuing to rely on the DB. What's the idiomatic way of using a local db with redux?
Currently my app is composed of several container components that each fetch data from the db in componentWillMount. One option for integrating redux is to keep this mostly the same, with the only difference being the state is kept in the store and data is fetched using actions and thunks.
Alternately, I have seen lots of example code that loads all the data into the store at launch. This makes the whole app more deterministic, easier to test and reproduce. Switching between the main components would happen instantly (at the expense of initial app load). But I lose the benefits the DB provides like indexes and nice queries.
It seems like it would be unreasonable load literally the whole db into the store, at least in my case, that would be about 10MB of data, maybe more. So I will always have at least some components which will need to continue fetching their data on mount. But there's a subset of data which is central to the app and can be argued that table should be loaded in its entirety (this would be about 5,000 to 10,000 objects, probably).
What's the idiomatic way to work with local storage and redux? I get the sense that async fetches in componentWillMount is not idiomatic if it can be avoided. Even in instances where the state is small enough that it can be fully loaded into the store, is it worth giving up the benefits of a nice efficient query interface?
Edit: I should mention: I am using Dexie, which is a really, really wonderful library for working with indexedDB. It's fast, has a nice query interface, handles migrations etc... I'd really like to continue using Dexie unless there's a really strong reason to do otherwise.
For reference, here's a discussion on this topic on Dexie's github. The general take away form that is "it depends". Not quite the answer I was looking for, so I am hoping to get more insight if possible.
Answering this myself with what I've discovered so far. If I better answer comes along I'll be happy to mark it accepted.
TL;DR: It really does depend. The idiomatic way to do things is indeed to put as much in the state as long as makes sense. However, it is not un-idiomatic to asynchronously fetch data from elsewhere when it makes sense. Many applications would simply be impractical otherwise.
Dan Abramov's egghead tutorial (even titled "Building React Applications with Idiomatic Redux") goes with the approach of having all state in the store and persisting it a s one giant blob (or the relevant slice) periodically.
This has the advantage that you use the redux store as usual and persistence is essentially transparent. If your data is small enough where this isn't a problem this is great.
As #seanyesmunt noted, there is redux-persist, which basically does a more sophisticated version of this.
Of course, shortly after that he then rewrites the tutorial to fetch data from an API. At this point you can just pretend that API is IndexedDB instead, it's really no different. You lose some benefits of redux by not having completely deterministic state as a whole, but in many cases you have no choice.
I ended up doing essentially the same thing as Dexie's Redux sample code. Basically, using thunks to async write to the DB on certain actions.
EDIT 2020-12-18: I recommend using dexie-react-hooks and the useLiveQuery() hook. It's an amazing experience to work with takes away all complexity around this. See also this blog post about it.
My old answer was:
This question is of large interest to me as well as I have been elaborating with react and dexie for the last project I've been in. I am personally examining how graphql could address this scenario, but I am still learning. I hope to provide an example of a graphql/dexie. Of what I understand, graphql would act as the service layer and its "schema" (backend store) would use the dexie queries required to produce the more flat an simplistic graphql data requirements. I will be looking at some ready-to-use grapql sample from Apollo or Facebook to get started and I believe it will be simple to use.
I generally don't think it scales to read entire db into memory. And I believe application startup is crucial to end users so I really hope to find a perfect architecture for this. And currently my hope goes to Graphql.

Is there a way to deveop by each module with react, redux, side effect

I'm developing Web project with react.
But bigger code size the speed is slower. And All code in one system is easy to be complicated and hard to maintain
Is there a way develop by each component with redux, side effect all in one module?
For example, modulizing one component(comtainer) with is's action, stores, side effect. And attach main code with build system..
At the end of the day, a single store will contain all state in redux. The exception to this, is if you choose to run two seperate apps on the same page - but they wouldn't be linked in any way whatsoever (so ignore it).
However, you can use combine reducers to join reducers from multiple components into one store while keeping them separate. For the majority of apps this will suffice completely, and I would find it hard to imagine it would cause performance issues unless it is set up incorrectly.
Your question doesn't lend itself to one concrete answer, but rather patterns. I would look into "ducks" for redux - its not a technology or library, but rather a pattern for keeping your stores and components modular.
Ducks: https://github.com/erikras/ducks-modular-redux
Explanation: https://medium.com/#scbarrus/the-ducks-file-structure-for-redux-d63c41b7035c#.36dsdqd5q
Personal favourite structure doc: https://hashnode.com/post/tips-for-a-better-redux-architecture-lessons-for-enterprise-scale-civrlqhuy0keqc6539boivk2f
If you still feel like redux doesn't align to your modular app, you can consider not using it - sometimes there is no need for it. https://medium.com/#dan_abramov/you-might-not-need-redux-be46360cf367#.p7j6cioou

Application design: how much Redux state?

I am currently working on building a small-ish app (6 front-end container-style components, 15 backend DB tables), in React.
I'm playing around with importing Redux, and I'm having a hard time designing my application state. It seems that I'll need to store broad-based state (e.g. user sessions) into Redux, but most of the other state I'll be pulling from the backend and won't necessarily need it to be always up-to-date 100%.
Based on all of the "redux-todo" style examples out there, it would seem that folks would store everything in their Redux store (since the state is relatively small, I suppose).
However, for my case, I'm wondering if Redux should just be a super lightweight store for only that which needs to be persisted across the app, a la an Ember-style 'service'.
Am I thinking about this correctly? Or should I be looking to store more state inside Redux?
I've struggled with that exact issue. It really takes some getting used to, but as another answer said, if you're using Redux, the idiomatic approach is to store basically everything in the Redux store. The one exception (and these turn out to be rather rare) is UI-only data such as a visibility toggle or dropdown info that sets a class or the like. That is, data that is ephemeral and has no impact on anything outside the component in which it lives. Even then, you will find that some UI-only items are easier to manage using actions and reducers as they often end up touching other items.
Edited to add: as the comment below states, the official Redux docs don't take a position on this issue. Which is one reason why so many people struggle with these issues -- you have a ton of freedom how to structure your React/Redux apps. My advice should be understood to be advice based on the experience of trying different approaches. Here are the three main reasons that I've seen for putting state into store:
more often than not, something I put into state ended up being needed somewhere else and getting it there through props required more work than if I had just put the data in the Redux store to start with.
Additionally, it's common to refactor your app to split apart components into more modular reusable pieces as your app grows and gets more complex. If you have data in state that is used in two places in a component you then won't be able split that component into smaller pieces easily.
Finally, readability. It's nice to be able to glance at your mapStateToProps call and see exactly what props are received or used by each component.
The problem is that Redux and putting everything in the store can feel like a lot of unneeded complexity when the actions and impact of the items is simple. If that's the case, I would suggest you consider dropping Redux at least at first. It will be a lot of work to refactor, but it will help you appreciate just where Redux shines. On the other hand, you may in fact not really need it for your app.
Back to your original question, yes, in my opinion, you should be putting more in the Redux store. Everything goes in there with a few very narrow exceptions. Data from the backend in particular should go into the store as a first step before getting mapped to props in the components where it's used.
The idea is to store any state your app needs to function. Your React components don't know anything about data other than what to do with it once they have it. The React/Redux "way" is that the only way they get it is from your Redux store.
So if you're fetching a list of items on app load, that goes in your store. Then your app has it for the entirety of the session. If someone leaves and comes back, or reloads the page, it fetches again, and stores a fresh copy in Redux again. You may not create any actions to modify it once it's there, and you may not need to fetch it again any time soon, but that's where it should live so your components can get stuff from it.
If you didn't store it in Redux where would you put it? And how would your components gain access to it?

Resources