perf: update to zustand 4 to prevent re-renders #4885
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Problem
#4766 #4764 highlights some performance issues that form builder has. Both videos show that lag that occurs after changing input. (#4766 unable to scroll to bottom fully is probably a separate issue fixed in #4860). This should be caused by a long JS task blocking interaction. I also experience this lag in local development, and this issue might exist across devices as it is relatively easy to increase the lag by adding more form fields.
Findings
Did a bunch of random digging to see whats the problem and I try to summarise them here. Note: the numbers here are in local environment, so I'm not sure how it translates in production
Solution
One thing I noticed from the profiler sessions is that the zustand library uses an increasing counter to force updates when state has changed. That's why there's a number of components that seemingly don't need to update but still do as they call the zustand hook. It turns out that the library has already been update to v4 which uses a different way of state management, so I simply updated to see if it helps.
I'm actually surprised to see how much improvement there is after the update. The JS task duration drop by about 30-40% from ~800ms to ~500ms and there is definitely less re-renders in React.
Therefore this, this PR is just a simple low-hanging fruit optimisation, but one that reaps noticeable benefit. If its worth it, there is definitely more room for improvement. Based on the findings above, I not sure if there is a simple solution to optimise performance. I'm still not too familiar with the overall state management in the app, but I feel some rejigging of the the state management should help. Maybe you guys can give your opinion on this.