React state: does changing state twice guarantees triggering render twice too? - reactjs

In React: Does changing state n times also triggering render n times too?
Is there any way to ignore some state changing based on the max browser fps rate?
I'm not sure using useTransition. It seem on experimental stage.

I recommend reading this article about batch update if you mean by different state object changes. But basically, no. It doesn't guarantees triggering render n times following state change.
As for limiting it using browser fps rate - it's an interesting question. I guess it can be implemented using requestAnimationFrame the way libraries like use-debounce are implemented

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 to put a timer that updates a Redux store?

I'm building a game and there's a score which updates every 5 sec with a timer.
Currently the score lives in a nested Component's state, but I'd like to make it available to other Components as well so it can affect their states (eg. higher score would affect the whole game's background color, the counters on top, and trigger pop-up messages).
I have Redux stores, and it feels like the right place for this score, but which component should be responsible for updating it/have the timer running?
Thanks!
It doesn't matter. Since we need to use setInterval for the timer, it can be placed anywhere in your app(as.. from any place it will work same because of the setInterval working mechanism).
But for better code/logical understanding, I would use the same component/method which I am using to start the game for starting the interval.
make a redux folder in which you'll have store.js file and your counterSclice.js files and here you put your update to count inside reducer.

Subscribing to Redux - React props issue

So I need to implement this function that checks the Redux variable in interval, say 5 seconds. My issue is that this variable is the content of a large, editable text; so subscribing to it normally causes app lags (because every typed letter is a variable's change).
Does anyone have an idea how to overcome it? I can post some code if you want, I just thought it's rather a theoretical problem..
Maybe I can render this component just every 5 seconds to avoid it being connected constantly?

Redux Selector or Effect

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.

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