Intro to re-renders in React
Dev Pukar
Posted on November 24, 2024
In one of a large application I have been working from past 6 months, I found a slow performance when opening and closing a modal whose toggle button was present in header. The modal took almost 1 second to open and close each time. This is the common mistake I see in lots of code written by junior react developers and me myself also have been making this mistake. If you want to be a senior react developer, you should be using the built-in hooks, rather than building custom hooks. React itself has a lot of built-in hooks for solving almost every optimization problems.
Example Code:
Problem: Modal took longer time to toggle
Reason: Every time the state updated, the whole component re-renders which makes the dialog slow. You can check this using console inside this components.
Solution:
For this particular problem, we should always try to lower the state as much as possible. Lowering the state means keeping the state near to the components that updates or needs it. The component that updates the state and the component that uses the state can be wrapped as a single component and rendered back to original place as a single component.
Solution code
Now, whenever the state update the and components are only re-rendered. This technique can save your time for building custom hooks or installing packages to optimize codes.
Posted on November 24, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.