Redux Selector or Effect - reactjs

Please help me to make the decision, regarding which technique to use.
I have a big list (up to million rows) that is kept in redux state.
Once user types in filter criterion, I want to apply filter and show filtered data (actually piece of it with react virtualized).
I do understand that ideally this is a use case for simple selector (or memoized reselect).
The problem that I see: filtering itself may take 2-3 seconds, thus, I have to use debounce. For debounce i have to use middleware, because debouncing is asynchronous and impure.
Can effect (epic) take data from state and act as asynchronous selector? Or maybe there are some patterns for implementing debounce in selector?
Appreciate any advices.

I have a big list (up to million rows) that is kept in redux state.
Really? You're doing blunder mistake. This will consume huge memory. And some browser may not respond them correctly.
So, I would suggest you to apply filtering from database results. On each filter being applied, the application will need to get the results from the database say upto 10, 20, 50, or 100.
With this sense, you can keep using redux or use memoized effect depending on your application logic/complexity. Both will work fine without worrying about debounce method.

Related

Get isLoading state of manually initiated RTK Query mutation

I'm working on a Nextjs project with RTK Query. Can someone tell me how to access the isLoading state of the mutation that is initiated like this https://redux-toolkit.js.org/rtk-query/api/created-api/endpoints#initiate. I don't want to use the generated hook useLoginMutation but instead get the data by unwrapping the returned result after dispatching like this await dispatch(api.endpoints.login.initiate()).unwrap() because I don't want my form to re render. Thank you in advance!
because I don't want my form to re render.
Hi, RTK Query author here.
Generally, you can use the selectFromResult option to reduce the amount of fields returned from the hook, and as such also reduce the amount of rerenders (as less things are changing).
Generally though, I have to strongly advise you: don't care about the amount of rerenders on this level. React is made to fastly rerender your components. One, two, or even five rerenders within a 1-3 seconds frame should not make any difference for your application - usually, your component will rerender on every keypress in your form anyways!
If, and only if you are seeing actual performance degradation, you get to the point of optimizing things like this - and then you would see if somewhere you have dozens or hundreds of rerenders, but still do not care about single-digit rerender numbers. If single-digit rerenders are a problem for you, you have heavy computation logic inside your components, and you need to optimize that - the execution of one of your component functions should always be in the sub-milliseconds. Then that's the place to optimize.
As for triggering the mutation with initiate: It will be loading until your await continues and done after that. If you just need that information, there is no need to access an isLoading state. You must set the component state if you need that information in your component. And that would trigger a rerender. You see where I am going: use the hooks! That's what they are made for.
Also, if using initiate: make sure to unsubscribe the result afterward or it will stay in cache forever. Again, this is something the hooks do for you.

Where should i handle sort in redux-saga?

I want to sort the data received from an api. Should I sort in the saga function and then save it to reducer? or Sort the data just before updating the store in reducer? or Should I sort in UI before rendering?
Depends.
Lot's of it comes to personal preference, some people prefer to do as much as they can in a saga and have reducers as simple as possible, others prefer to use sagas only for side effects and keep most data transformations to the reducers.
Most of the time it doesn't matter much, but in some cases there are things to consider. For example, if you know an action is going to get dispatched from multiple places and you will want to sort the data in each case, it might make more sense to do the sorting in the reducer, rather than doing it multiple times at those different places where the actions are being dispatched.
I found that for such data transformations it is best to have an utility function that will do the job. You can then call this function in either saga or reducer - it will be nicely "hidden" in whichever place you decided to put it to and it will also be easy to switch it to the other place if needed.
You also mentioned components and you are right, often times you will want to do transformations such as sorting during render and not when the data are stored, especially when e.g. the sorting depends on another application state like selected sort option. If you have a connected component, use reselect selectors to memoize such result so you are not sorting the same data again and again on every render. If it is some transformation done deeper in the react tree you can't handle with reselect, use something like memoize-one (class components) or use useMemo (function components) for the same effect.

Million options in React dropdown

Is there a better way to implement million options in dropdown. In my case there can be more than one million users and I need to select one user at a time. I have one choice, make asynchronous call for each letter when typing and I can filter the users. Is there any other methods to implement? If I bind all the options to dropdown, will it make my app slow?
You can do it in 2 ways. One is what you already said yourself. Making async calls. Or you can also do it a simpler way, This will still have a huge performance boost. It is still not very advisable to filter on the client-side for a million items. But nonetheless, it's possible and I haven't seen any major performance hit.
Use a state variable to maintain what you are going to render and another static variable to maintain your entire million collection.
On search, you filter that one million list and assign it to the state variable.
Render only the items that are in the state variable.
Tip: Make sure your filter method doesn't return more than say, 1000 items at any moment, this will force the user to enter more characters to search and it will keep the UI smooth.
Yes, having a big list to render will make your app slow as it will have to mount and unmount when the user is typing. Ideally the client should send requests to server by using debounce or something to limit the requests and server should send a paginated response / top X number of users which match the input.

React Redux anti pattern to calculate and store results in store?

I have at least two approaches to solve a problem.
Repreform calculations inside views on each update (map, filter, find)
Keep an "CurrentState" object inside my redux state.
I choose to create a CurrentState object that stores my calculated result (It calculates the results inside the reducer function).
Approach 2 saves processor calculations, but it feels dirty.
is it considered an antipatern to have a CurrentState object (updated from the reducer) inside the state?
Thank you in advance!
Not totally clear from your question - but I assume that you are talking about situation, that you can compute "result" from other data in your store and asking if storing it (redundantly) in store is good pattern.
Well, generally I would not recommend it as keeping redundant data in store can lead to inconsistent data bugs - if you forgot to keep your data in sync (e.g. when you or someone else working on the project would change one data and forget to change the order place).
The standard patter for this is usually to use selectors and memonization (see https://github.com/reactjs/reselect). The idea is to keep only normalized data in your store but to use selectors in your views. Selectors are responsible to "cache" (memonize) extensive computation. Another advantage of selectors is that it provides level of indirection for your application and you can easily evolve your state (as the project grows) without affecting your whole application. On the other hand for small and one time projects selectors can be just "another" boilerplate - but in general I recommend to use them.
This was a hard anti-pattern.
If you are reading this chances are you don't fully understand redux and I would like to recommend
https://github.com/leoasis/redux-immutable-state-invariant

React performance in mobile browser

I have a component (table) that contains many lines with data editing in them, with masks in the form of contenteditable, it is possible to select all fields and change all the lines at the same time.
On desktop it works pretty fast, but on iPhone 6 I have unreal lagging, with Safari hanging for 20 seconds for each action.
I completed the recommendations to improve performance from React: prevent reconciliation, pure components, etc ...
Are there ways to improve performance? Is it necessary for me to ponder a functionality change on a mobile device, in favor of performance?
You should override shouldComponentUpdate component life cycle method for every row of the table. Ideally for every cell in every row.
If you have a table and it gets a different props. What happens is that every nested component gets re-rendered. PureComponents might help but writing shouldComponentUpdate is the only way to really control when something gets re-rendered.
Also for really large data list there is a react-virtualized. Check it out. Its pretty cool.
It would be nice if you could post source code though.
Adding to above answer, you should use react-perf module to exactly validate if any change actually made a performance gain.
https://github.com/crysislinux/chrome-react-perf
use this extension to exactly see how many times, each component on your page actually rendered, when you did your problematic/slow user interaction
try reducing no. of renders of each component. Also reduce the no. of components rendering on each such interaction.
try minimising time taken by each component. You can sort by time and focus on the most expensive components. Avoid rendering components higher in heirarchy, first. To find the exact reason behind a component's rendering use following method.
Put componentWillUpdate lifecycle hook, temporarily, and diff previous and next props/states. With this you would get the exact prop culprit behind a rendering. Unneccessary prop change might be in following scenarios:
When prop is just a function which is changing because of 'bind' usage or arrow-function usage, which changes the function reference everytime, and with that, causing new renders, everytime.
There might be a prop being initialised with new Object() or {} notation, which is considered new object everytime and hence new rendering. This can be avoided by a const READ_ONLY_OBJECT = {} and using READ_ONLY_OBJECT everytime a variable needs initialization.
You might be unnecessarily mutating object-type props and doing diffs in componentWillRecieveProps.
There can be more reasons to where we dont want a render but it happens because of the ways react works. Just see that props dont change unnecessarily. Also, dont put unnecssary componentWillRecieveProps/shouldCompoentUpdate checks as it can impact performance negatively. Also when using these, use these as higher in heirarchy as possible.
Some techniques to use
try to avoid using react lifecycle hooks which run on each render.
try reducing any scripts runing on every render.
use componentWillReieveProps, but only if you gain, else point 1 can reduce gains also. Also, using this often can lead to non-maintainable code. Always validate the gains with react-perf tools, before making changes related to optimizations.
use throttling in chrome-dev-tools to create slow device enviroments, use javascript profiling to see which javascript methods took most time.
Try using redux with react, to manage state. Redux also has componentWillReieveProps thing implemented for connected components. So, using redux will help.
When using redux use an appropriate batching stategy. You can also use batch middleware in redux.
Also, similarly, in react try to do events in batched manner so as to reduce amount of time spent in react's renderings and diffing algorithms. Try clubing setStates in react or actions in redux to reduce react scripting time.
Always use appropriate throttling/debouncing techniques while implementing input controls, to get immediate response. You can also use uncontrolled components to have immediate response, if your business logic allows. Idea is to not to run any javascript when user is typing or interacting with your page in any way, else he would notice the jank in devices particularly bad in computing power.
Your action handlers should not be lengthy. If lengthy, try to do them in chunks, asynchronously, with redux-actions or with just promises.
There is more to this list, but the problem is, react as a framewaork is pretty easy to get to work, initially, but sooner or later, any medium sized react app will run into these performance problems, as react's diffing and rendering logic incurs a lot of performance penalties in bad devices, as soon as app grows in size, only option is to get react-performance tools, also, into the build process, asap. This will let you validate and measure your improvements.

Resources