Performance issue with React - angularjs

I read about React being very fast. Recently, I wrote an app to test react against angular. Unfortunately I found react performing slower than angular.
http://shojib.github.io/ngJS/#/speedtest/react/1
Here is the source code for react. I'm very new to react. I am sure I'm doing something wrong with my react code here. I find it unusually slow.
https://jsbin.com/viviva/edit?js,output
See if any react experts can find the bottlenecks.
Update 1:
Removed the usage of context.
Better usage of setState.
Better usage of shouldComponentUpdate.
I still can't make it faster than angular or even close to it.
https://jsbin.com/viviva/96/edit?js,output
Update 2:
I made a big mistake by creating 2d arrays in the cell component. So I moved them to a mixin. Now I believe that react is faster than angular in DOM manipulations.
https://jsbin.com/nacebog/edit?html,js,output
Update 3:
My mistake again. I did it wrong which made it faster. After analysis, it was rendering incorrectly. If anyone can help me understand, if this could be any faster. I know react is not good at dealing large arrays. In this scenario, it's dealing with four 3d arrays. https://jsbin.com/viviva/100/edit?html,css,js

React's performance is exaggerated. It's fast enough for most real use cases. Rendering large lists is its main weakness.
Also this always returns true (unless the update is triggered by setState). You need to shallow compare the props.
shouldComponentUpdate: function(nextProps, nextState) {
return this.props !== nextProps;
}
And you should be using props in the places you're using context.

This is a very contrived example in my opinion.
As stated above, you are using context incorrectly.
There is no need for a mixin: the number of columns and rows can and should be passed down as props. create2DArray, getRandomNumber should be declared at the top of your script as simple global functions.
You are setting the state incorrectly. You should never change the state like this this.state.some = 'whatever', you have to use setState
this.setState({ some: 'whatever' });

You're using context incorrectly, the documentation states:
In particular, think twice before using it to "save typing" and using
it instead of passing explicit props.
It's mostly beneficial for passing context objects like currently logged in user or perhaps a redux store. Your app is using context when it should be using props.
You'll need to ensure that shouldComponentUpdate is a meaningful predicate. See https://facebook.github.io/react/docs/advanced-performance.html
If you correct those two things it'll be a better measure of React's performance compared to Angular. At the moment you've got a well tuned Ferrari running against a model T Ford (held together with chewing gum).

Related

useContext with immutableJS

I have an Object of data that I store as my context. It gets filled with API responses and I feel like performance-wise I'm doing something wrong.
I tried to look into ImmutableJS but there is no reference of combining ImmutableJS with ContextAPI. Is combining them together doesn't give any benefits? And if it does do have an example of to how develop such a thing?
Whether you use context directly, add redux or pass down props through your component makes no difference to how you use immutable. ImmutableJS simply makes sure that an object does not change unintentionally and that it can be checked for changes with fast reference equality.
The problem you describe could arise from the fact that your context object changes whenever any response data is modified. Therefore it would trigger a rerender on all context consumers (see caveats). I like Immutable and use it in a large project, but if I am correct, it won't make a difference, you would have to fix the root cause or handle changes with shouldComponentUpdate.
I suggest you look into redux (or some other context provider) or show us code.
Don’t try solving your problem by introducing a dependency. It won’t be a magic bullet.
From what you describe, your context object changes frequently and is causing your component tree to rerender too often.
Maybe try creating multiple contexts that are only relevant for parts of the app. That way rerenders will only happen with subtrees using specific context.

React Native - Application Performance Issues With The FlatList?

I completed my application in react native but after building its slow. Then I started to research to improve the performance of the application. I found this documentation on the official website of the react native and I am sure this will help me but I am unable to get it into my head. Please can anyone tell in easy words what the following documentation is saying:
If you are using immutable data structures, this would be as simple as a reference equality check.
Similarly, you can implement shouldComponentUpdate and indicate the
exact conditions under which you would like the component to
re-render. If you write pure components (where the return value of the
render function is entirely dependent on props and state), you can
leverage PureComponent to do this for you. Once again, immutable data
structures are useful to keep this fast -- if you have to do a deep
comparison of a large list of objects, it may be that re-rendering
your entire component would be quicker, and it would certainly require
less code.
I will be glade. Thanks !!!
If you're using a static object, you can render your component as a PureComponent like it says above. Then, you can pass it props or set the state with the words you want displayed.
When you do that, the FlatList will re-render only the portions of the data that it needs to, depending on what changed. What the last part of it is saying is that a PureComponent does shallow comparisons - if something in an array changes, but the array itself doesn't change, then your FlatList won't update. However, with an immutable object, you can always declare it as a PureComponent and it should be faster.

Redux selector pattern and performance

I've come across this link that briefly describes the advantages of the Redux selector pattern:
https://gist.github.com/abhiaiyer91/aaf6e325cf7fc5fd5ebc70192a1fa170
They provide an example of calling the filtering inside mapStateToProps:
function mapStateToProps(state) {
return {
incompleteItems: getIncompleteItems(state)
}
}
However, since mapStateToProps is called whenever a state changes, even if the change is completely unrelated to the items list, isn't there a performance penalty in this case? wouldn't it be best to do the filtering inside the reducer?
Thanks.
The above code snippet just mentions that you should extract the "calculations" from your mapStateToProps function to another function.
The other function could be easily testable and the best part for what you mentioned of not recalculating on each cycle.
Now we can reuse this logic across many components mapping this exact state! We can unit test it as well! More importantly we can now memoize this state with reselect
in this case, you can use reselect package
https://github.com/reactjs/reselect
and that will take care of recalculating or n
There would indeed be a wasted re-render if you've bound to a prop which didn't actually change, but your other props did. There are 2 things you can do in this case -
Use shouldComponentUpdate -
You can go ahead and implement a shouldComponentUpdate lifecycle method for your component. Simply checking for the change for the prop and returning false, will give you immediate results.
Use Immutable data structures -
You can ( and should in my opinion ) use immutable date structures for your application. This not only allows you to help better reason about your app, but also with debugging. Using immutable data structure for your local states will allow for advanced memoization patterns and optimizations.
Check out immutable-js by facebook for more details.
State modelling - This is not really a thing we developer think a lot about while coding our super cool apps, but this a worth thing to consider while think in the direction of perf. Keeping re-renders local to the actual data changes is a painful task, and tools such as reselect, immutablejs and side-effect management libs such as redux-saga and redux-thunk, help a lot.
Hope this turns out to be useful for you! Cheer! 😇

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.

Using a closure to encapsulate state for React components

When passing data between two elements that are very far away from each other in the hierarchy of components, passing data through props can be tedious. In these use cases I've resorted to using Redux just because it is less to keep track of when there is a large amount of components.
What I've done in one little project is to use a closure to encapsulate state and export that variable and consume it elsewhere. I feel this is a an antipattern but it does work.
The way it works is by declaring some variable that is going to be modified within a component. This same variable is the imported from elsewhere and consumed from elsewhere.
Here is a small sample with what I am doing (just pretend there is a large component hierarchy): https://codesandbox.io/s/2R9RvYkN1
So my questions are: is there a better way to achieve the same results? Should we use a Flux implementation for these use cases? Is it ok to just pass props around through a large hierarchy of components?
As you stated yourself, redux solves this problem by providing an "App state" that's global to your app, which allows you to connect any component you want to that state.
Your "closure" is merely a poor-man's Redux, it's also a global state, only it lacks any of the features provided by Redux(unless you write them specifically).
let's CompA needs to re-render based on a click event on CompB, how do you do that automatically with a closure? you'd have to add listeners, check if a relevant state was changed and then re-render.
all these things are done for free by Redux, so I don't see any added benefit(except for not using redux, which can be a benefit in it's own).
If it's that important not to use redux, this can be "fine", yet very dangerous and I'd say it won't scale well.

Resources