Where should I store the local state of a Redux middleware? - reactjs

I’m using Redux to manage the logic of a music player. When it’s playing something and suddenly fails, I want to be able to intercept that action and make the player start again, but only n times, as I don't want to keep automatically retrying forever if the problem isn't recoverable.
I think a middleware is a good option to implement this, but I’m wondering if I should store the number of retries already done for a certain item either in the global state, or locally in the middleware.
A more general question would be if a Redux middleware should contain any local state at all, I mean, state that only it cares about.

In my opinion (and based on limited information about your specific project):
you should configure the n value via the middleware constructor, and
you should store both n and totalRetries in private variables of the middleware.
Why?
Choosing where to store your middleware state shares similarities with deciding between component state and redux state. You can use the same questions as a guide:
Do other parts of the application care about this data?
Do you need to be able to create further derived data based on this original data?
Is the same data being used to drive multiple components?
Is there value to you in being able to restore this state to a given point in time (ie, time travel debugging)?
Do you want to cache the data (ie, use what's in state if it's already there instead of re-requesting it)?
Do you want to keep this data consistent while hot-reloading UI components (which may lose their internal state when swapped)?
As Dan Abramov said:
The way I classify it is when ever state needs to be shared by multiple components or multiple pages and we need to persist some data over route changes, all that data should go inside the redux store.
You can map this idea from components to middleware by rephrasing "…persist some data over route changes…" to "…persist some data over [insert relevant boundary here]…", for example closing and relaunching the app.
The totalRetries doesn't seem to represent a meaningful state of the application. It has to do with some "behind-the-scenes" I/O operation that wont persist across closing the app or sharing app state with a debugger. One might even argue that you should not expose it to other components via redux state, lest they rely on (potentially shifting) internal workings of your middleware.
redux-saga, etc allow us to write this type of functionality in a very neat and testable way without having "exposed wires" in the application state or module namespace. You could use a saga to encapsulate your entire "play audio" behavior.
Exporting a reducer and then accessing its compartmentalized "public" state from your middleware introduces quite a bit of unnecessary complication.
If you want to expose totalRetries and n to other components, you may do so via an action, such as PLAY_AUDIO_RETRY with the action containing both variables in its payload.

Related

Callback in Redux/Redux-Saga is an Anti-pattern?

Let's figure it out,
An user performs a login submission, so app shows instead a
Submit button a Spinner, a self contained state whose help us (isLoading).
Okay, when application send to saga login action we can pass a callback
for set false loading state when login submission has successful or failure.
Some experts will say, manage loading state in reducers, but carry to all whole application
loading state, for some specific action not sounds good.
The problem with callbacks is that the architecture doesn't guarantee that the callback gets called or that it won't get called multiple times. That is because redux actions are essential events - where each event can be handled by 0-n handlers (or sagas in our case).
Of course at the time of writing you know that that particular code is handled exactly once, but for anyone else this might be hard to grasp unless there are strict rules in the project how to handle this.
At the same time, you are right that putting local state to redux store isn't great. I usually deal with this by moving the data logic to its own structure. So e.g. loading collections of items from server is no longer local state of some component bur rather global data state that can be used and reused by multiple parts of the applications. This will also make it easier to have custom caching logic for the data cross whole application etc. However, some local component state in redux is still unavoidable for some specific backend calls.
In terms of future, I saw some attempts at useSaga hook, which would work on top of local useReducer hook and therefore local state, however the implementation for such logic is still limited because the current react hook api lacks certain functionality that is necessary to make sure this works well with react commit phase, render bail outs, reducer reruns etc.

Maintaining the full state of a React app in the backend?

I'm building a real-time "lobby" type web app that hosts multiple users (2-8 at a time), where the state of the lobby is shared among the users. The UI is built with React. Each user establishes a websocket connection to the backend upon joining the lobby. At this time they receive the full global state of the app as a JSON object (its size should not exceed a few kilobytes).
I'm having difficulties conceptualizing the precise state maintenance scheme, and would like to hear your views about it, once I've described the situation in more detail.
The lobby presents to the users a number of finite resource pools, access to which is shared by everyone. The users will move these resources between each other as well as to and from the pools. My current thinking is that the full state of the lobby and all of its resource pools is stored and maintained exclusively in the backend. When a user wants to move a resource e.g. from a pool to themselves or vice versa, or to change the visible state of a resource, this is done with JSON messages sent over their respective websocket connections.
Each action they perform causes a message like this to be sent over the socket (simplified):
{
"action": "MOVE",
"source": "POOL1",
"target": "user_id_here",
...metadata...
}
The users send these messages concurrently at arbitrary times and intervals, and the backend (using a Python asyncio-based server and a data store still to be determined) receives them serially, reconciles each one with the global state in the order they arrived, and then sends the full updated state of the app to every user over their websocket connections, for every single message received. The user who performed the action that triggered the state update additionally gets a status object informing them of a successful transaction, which the UI can then indicate to them.
When a user sends an action message that is impossible to reconcile (e.g. another user has exhausted a resource pool just before their message requesting a resource from that same pool came in), the app still sends them the full up-to-date state of the app, but a status object is included, containing information that the UI uses to inform them that their action could not be performed.
So far, so good. Given the types of actions, types of resource pools, number of users and size of state objects that are to be expected, the frequency of updates should not become a problem, neither in terms of resources nor bandwidth use.
To clarify: none of the actions that the users perform in the React UI mutate their local state in any way. Each and every action they perform is translated into a JSON message like the example above, and the result of that action will be receiving the updated full state of the app, which fully replaces the previous state that React used to render the UI with. The React-level app state is ephemeral, only used for rendering it once. All renders exclusively happen in response to state updates over websockets.
The one area that I'm having difficulties with is how to structure that ephemeral state on the React side so that rendering the updated state object is as quick and efficient as possible. I'm a backend guy and have no prior experience in building a React app of this nature (I last used it four years ago in a really ad-hoc manner, passing props to deeply nested child components, with state stored all over the place). I'm not quite sure what facilities and tools to use.
For example, I could use a top-level context provider with the useReducer hook, touted by many as a "Redux replacement" (which it technically isn't). Or, I could use Redux, but does it actually add any value in this case? Or something else?
Given that the whole state is replaced as a result of every action of every user, what is the best, most efficient, least render time-requiring way of structuring the React side of things?
I would like to suggest that you do not send in the entire state of each and every user over the network instead just send in the modification and let the individual users apps perform the change handling. Once you make this change you could make use.of redux and store the states in a reducer. Also doing this will help you avoid a lot of re-renders as the object references will not change for a lot of your components,
Another thing to add here is that you can store the redux state in the localStorage when the session is terminated
FurtherMore, the one problem that you could have here is that when the user re-connects, he might not get the changes that happened while he was online.
To solve this, you can maintain a transaction id for each user so that the user is sent all the data post that transactionId till the current state by the server and then the app can process and update the transactions
Or the other approach if to completely fetch the data when the user connects for first time or reconnects.
As far as using useReducer or Redux is concerned, you need to decide that based on the complexity of your App.
Cases where the app is small might easily be covered with useReducer and useContext but if you states are complex and you need to maintain multiple reducers, you should go ahead with Redux as it provides moree flexibility with data storage
EDIT:
If the only solution for you is to send the data totally to frontend and let the frontend render it, then you need to divide your frontend code into various simpler modules as much as possible so that no component is using a a complex state.
Once you do that you can make use of shouldComponentUpdate or areEqual parameter to a class component or functional component respectively.
The idea here is to compare the previous and current value that you get from props and let go ahead with the rendering logic or not.
You can store the state as it comes to a reducer inside the redux state, that way, you would be able to implement selectors that are memoized and are able to return data which doesn't change if the actual value hasn't change.
Also while you are using connect for your React app component, its actually a functional component, so unless mapStateToProps returns a value whose reference changes, it will prevent the re-render itself since its a PureComponent
I would strongly suggest, you go through the documentation of shouldComponentUpdate, React.memo and redux. Also look into reselect library that helps you implement memoized selectors

What's the right approach for storing and accessing table data in a Redux store

I'm very new to ReactJS and Redux (but not development, in general). I'm trying to determine how best to approach a SPA I'm building.
My app will download datasets via API and display them in a spreadsheet. I'd like to use Redux to store the data. Is that the right approach? We could potentially be looking at very large datasets. Would it be more appropriate to only store the data that is currently rendered in the spreadsheet?
I'm totally lost as to an approach that would be efficient in terms of rendering speed and memory management as well as mindful of potential network issues as rows of data are requested from the API.
Thanks...
When you are working on a react/redux app, you generally will have two options to store your state: local component state or in redux. There are quite a few blog posts out there detailing when each is appropriate. This github issue comment from Dan Abramov, one of the creators of Redux, pretty succinctly sums it up
Use React for ephemeral state that doesn't matter to the app globally and doesn't mutate in complex ways. For example, a toggle in some UI element, a form input state. Use Redux for state that matters globally or is mutated in complex ways. For example, cached users, or a post draft.
Sometimes you'll want to move from Redux state to React state (when storing something in Redux gets awkward) or the other way around (when more components need to have access to some state that used to be local).
The rule of thumb is: do whatever is less awkward.
Both component state and redux state can be used performantly, so I wouldn't worry too much about that when choosing. From what you've described, the questions I would ask are
Do I need to have multiple spreadsheets of data loaded, but not all displayed at once? For instance, maybe you have multiple tabs of spreadsheets and you want to be able to tab through them without having to re-fetch the data each time
Do I need access to the spreadsheet data in a lot of different places, or is it fairly localized?
Will I be able to modify the data in the spreadsheet, and if so, how difficult would it be to perform those modifications using redux and without?
There are quite probably other considerations as well. In general, the advice given is to stick with just using React local component state until it starts feeling awkward, and then move to redux at that point. Oftentimes, components state is all you need, and if not you'll get a better appreciation for situations where redux helps.

Is it a bad practice to use stateful components bypassing redux?

Say, I don't want to keep my checkboxes state in global redux store. Cause I don't want to deal with actions and reducers for this small local state. So I want to explicitly use setState() inside my component.
Is it a bad practice (for instance, in testing aspect)?
Per the Redux FAQ entry on component state vs Redux state:
Using local component state is fine. As a developer, it is your job to determine what kinds of state make up your application, and where each piece of state should live. Find a balance that works for you, and go with it.
Some common rules of thumb for determing what kind of data should be put into Redux:
Do other parts of the application care about this data?
Do you need to be able to create further derived data based on this original data?
Is the same data being used to drive multiple components?
Is there value to you in being able to restore this state to a given point in time (ie, time travel debugging)?
Do you want to cache the data (ie, use what's in state if it's already there instead of re-requesting it)?
It's absolutely fine to keep the checkbox state in you local state as long as it doesn't depend on the data.
A good practise is to keep all you data in your redux store and the ui-related state in you local store.

Should you store Application state in local state or Redux Store

I have been working with Redux for almost a month now. My question is this that I am putting all my app data in the redux store, but should I also put the toggle states that helps me change my UI in redux state or should I simply manage that locally in each page by just doing
this.setState({ showActiveForm : false })
There is no right or wrong answer for this. To help you decide, here are some common rules of thumb taken directly from the redux documentation:
Do other parts of the application care about this data?
Do you need to be able to create further derived data based on this original data?
Is the same data being used to drive multiple components?
Is there value to you in being able to restore this state to a given
point in time (ie, time travel debugging)?
Do you want to cache the data (ie, use what's in state if it's already there instead of re-requesting it)?
Another advantage to keeping the majority of your UI state in redux is that you can write more stateless functional components and make use of the performance optimisations they will bring in future versions of React:
This pattern is designed to encourage the creation of these simple components that should comprise large portions of your apps. In the future, we’ll also be able to make performance optimizations specific to these components by avoiding unnecessary checks and memory allocations.
The current best practice is to use local state to handle the state of your user interface (UI) state rather than data.
Your case is the perfect example of the above. So the state to manage hiding and showing of a component must be within the local state itself and not redux store
Another example of UI data that you could store in local state would be the currently selected tab from a list of options.
A good way to think about when to use local state is to consider whether the value you’re storing will be used by another component. If a value is specific to only a single component, then it’s safe to keep that value in local state.
To elaborate further
Redux is also useful for triggering events for which you need access on multiple components or across multiple routes. An example of this would be a login modal, which can be triggered by a multitude of buttons all across your app. Rather than conditionally rendering a modal in a dozen places, you can conditionally render it at the top-level of your app and use a Redux action to trigger it by changing a value in the store.
Usually, the rule of thumb is that you use a redux store to manage data in your application aka storing items fetched from the server and local react state for ui behaviors, like toggles in your case. But it's not a strict rule, for instance, if you need to toggle something from multiple places it's easier to use redux for that
That depends on how your components are organized. If the state of toggle is used across multiple components then I prefer to manage the state via redux store.
If the the status is local to that component and if it is not used in anywhere else best thing to do would be managing the state within the component. Therefore the component will be self contained.
3 points that i consider when working with react redux
1.keep UI state and transitory data (such as form inputs) in local state.
2.keep data that you intend to share across components in Redux store.
3.Data that you fetch from Server should go to redux store.

Resources