How to optimize React component to render it ?
ReactJS mainly depends upon the props (which are passed to it) and the state of the Component. Hence in order to reduce the number of times Component renders we can reduce the props and state it depends upon. This can be easily done by separating the logic of one component into several individual child components.
The Child components will manage their own state hence parent component will not be called if any child component changes its state.
To Demonstrate it we will create a Demo React App.
Step 1: Create a fresh React Native Project by running the command
npx create-react-app demo
Step 2: Now go into your project folder i.e. language demo.
Project Structure: It will look like the following.
Now we will Create 3 Components Parent.js, Child1.js, and Child2.js
Working: We have now three components named Parent.js, Child1.js, and Child2.js.We have declared a counter state in all three of them and also a Button to increase the value of count.
- When the app loads for the first time all three of the components get rendered for the first time.
- Now when we click in the Parent’s Button the counter state of the parent component increases by 1, this results in the rendering of the Parent component as since Child1 and Child2 are rendered in the same component they both also get rendered.
- Now we click the Button in Child1 which changes the counter state of the Child1 Component, but this time only the Child1 component gets rendered. That’s because both the Parent and Child2 components are separate from Child1 rendering logic.
- Now we click the Button in Child2 which changes the counter state of the Child2 Component, only the Child2 component gets rendered. That’s because both the Parent and Child1 components are separate from Child2 rendering logic.
Hence we can easily separate components and states to reduce rendering.
It is useful when we have multiple lists in one component. If we just render every list in the same component then on change in one list will also cause another list to re-render. This will slow down the app. Hence separating each list in its own component will reduce re-render.
React often throws a warning of “VirtualizedList: You have a large list that is slow to update” which can also be solved by using a separate component to render each child.