Today, I am sharing with you a problem that is common with React from a performance point of view. I would not say problem but rather a development approach.
Problem Statement
React is driven from updates from action to state to view. So if we update something on the state, the DOM changes and causes a re-render. Consider a page with 10-15 inputs including text inputs, checkboxes and drop down with some large datasets. Now when we edit the form in a React controlled form input way (binding everything to state and updating the state when anything changes), any update to a single text box is going to leave your page un responsive. I know, if you have this in normal HTML, it would be ok but that’s just how React concept works.
Why is it like this?
This is just because every update to the state causes a re-render and drop down having multiple nodes is re-rendered on any single character you type in any text box. Leave about the possibility of having the drop down filterable and all.
The Solution
The solution is to implement a good user experience and keep the functionality intact by using below 2 techniques.
Avoid using onChange on Text Input unless it is required
You should always use onBlur for normal text input unless you really want the text input value to dynamically available to state every single character change. This is not the case for 80% of the scenarios.
There is no major change in your code. Just need to use “onBlur”.
[html]
<Input name=’name’ value={name} onBlur={(e) => this.setState({ name: e.target.value })} />
[/html]
Limit the data set for Drop down
In my case I was using Semantic React and the drop down was just hanging because I had a searchable drop down of 3000+ values. My approach was as below:
- By default the drop down can limit to 10 records or so to start with.
- When searching, pass a custom filter function and limit the number of records.
My results after these approaches were fantastic. Improved user experience and performance drastically!
Hope this helps!
Let me know approach did you choose for this problem statement?