reactJS. have created multiple charts eg bar chart, pie chart. when these charts are placed in dashboard and if i sort bar chart, pie chart also re-rendered. this reduces the performance if the dashboard contains like 5-6 charts and all charts get rendered everytime. How to make only the bar chart to render when i do sorting or limiting records of bar chart. This dashboard page is dynamic like one dashboard may contain 4 charts another dashboard may contain 10 charts.
I’m not very good in reactJS. how to achieve this in reactJS
2
Answers
You can use the useMemo() Hook. The useMemo hook in React is used for memoization, a performance optimization technique that helps in avoiding unnecessary recalculations or re-renders of a value (such as a component or computed data) unless its dependencies have changed. It’s particularly useful when you have a costly computation or rendering process that you want to avoid repeating on every render.
You’d want to create a memoized component.
I’ll give you an example using chart-js.
First, let’s create a scatter plot component. The key here is the
arePropsEqual
function, which is used to actually determine whether a re-render is necessary.Then go ahead and use this component in your main Dashboard component, something like this:
Now you shouldn’t get any more unnecessary re-renders, unless your scatter plot component’s props change.