Optimize Your React App’s Performance with React Tracked
The State of State Management in React
Over the past few years, managing state in React has undergone a significant transformation. With built-in solutions like React Context API and React Redux, it’s become easier to maintain a global state and track changes. However, one persistent challenge remains: optimizing performance by preventing unnecessary re-renders.
The Consequences of Excessive Re-Rendering
In smaller applications, excessive re-rendering might go unnoticed or have no negative impact. But as your application grows, each re-render can cause delays or lags in your UI. This is where React Tracked comes in – a library that helps track state usage and optimize performance.
Getting Started with React Tracked
To begin, set up a new React project and install the React Tracked library using the following command:
npm install react-tracked
Next, let’s create a simple global context with two counter components, each using one value. We’ll compare React Tracked with the vanilla React implementation of a shared state.
The Vanilla React Implementation
Create a store.js
file that uses the global counter context and the useSharedState()
Hook for the states in the counter component. Run the project and observe the output on the browser screen.
The Problem: Unnecessary Re-Renders
Open the browser console and hit each Increment button three times. You’ll notice that each component re-rendered regardless of whether the state was updated. Ideally, the component should re-render only when the state is changed.
Rendering a Large List
Let’s try rendering a large list of elements. Add code to both Counter1 and Counter2 to generate a list of 10,000 random numbers in each component. Observe the output on the browser screen and note the CPU usage.
Preventing Re-Renders with React Tracked
One popular method for preventing re-renders is using Selectors in React Redux. However, React Tracked offers a more efficient solution by wrapping the context object and returning its own provider using JavaScript proxies to track changes to the individual attribute of the state.
Implementing React Tracked
Modify the store.js
file by adding the following code:
“`
import { createContainer } from ‘eact-tracked’;
const { Provider, useTracked } = createContainer();
“`
Rebuild the project and compare the output from earlier to the output with React Tracked. You’ll notice a significant reduction in CPU usage and improved performance overall.
The Benefits of React Tracked
Using React Tracked, we minimized the number of times our counter components were re-rendered, decreasing CPU usage and improving performance overall. By optimizing our application’s performance, we can create a better user experience.
Take Your React App to the Next Level
Get started with LogRocket’s modern React error tracking in minutes. Sign up now and improve your app’s performance today!