Optimisation is the number one thing on every dev's mind when building any software, especially web apps. React is a JavaScript library for building user interfaces. React ships with several ways to minimize the number of costly DOM operations required to update the UI. Using React will lead to a fast user interface for many applications without doing much work to specifically optimise for performance.
When we create a rendered component, React creates a virtual DOM for its element tree in the component. Now, whenever the state of the component changes, React recreates the virtual DOM tree and compares the result with the previous render.
It then only updates the changed element in the actual DOM. This process is called diffing.
React uses the concept of a virtual DOM to minimize the performance cost of re-rendering a webpage because the actual DOM is expensive to manipulate.
The issue comes when the child components are not affected by the state change. In other words, they do not receive any prop from the parent component.
React nonetheless re-renders these child components. So, as long as the parent component re-renders, all of its child components re-render regardless of whether a prop passes to them or not; this is the default behavior of React.
Profiling the React app to understand where bottlenecks are
React allows us to measure the performance of our apps using the Profiler in the React DevTools. There, we can gather performance information every time our application renders.
The profiler records how long it takes a component to render, why a component is rendering, and more. From there, we can investigate the affected component and provide the necessary optimization.
1. Keeping component state local where necessary
import { useState } from "react";
export default function App() {
const [input, setInput] = useState("");
return (
<div>
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
/>
<h3>Input text: {input}</h3>
<ChildComponent />
</div>
);
}
function ChildComponent() {
console.log("child component is rendering");
return <div>This is child component.</div>;
};
Whenever the state of the App component updates, the ChildComponent re-renders even when it is not directly affected by the state change.
To ensure re-rendering a component only happens when necessary, we can extract the part of the code that cares about the component state, making it local to that part of the code.
import { useState } from "react";
export default function App() {
return (
<div>
<FormInput />
<ChildComponent />
</div>
);
}
This ensures that only the component that cares about the state renders. In our code, only the input field cares about the state. So, we extracted that state and the input to a FormInput
component, making it a sibling to the ChildComponent
.
This means, that when the state changes, only the FormInput
component re-renders, and the ChildComponent
no longer re-renders on every keystroke.
2. React. Lazy for Lazy Loading Components
To implement code-splitting, we transform a normal React import like this:
import Home from "./components/Home";
import About from "./components/About";
And then into something like this:
const Home = React.lazy(() => import("./components/Home"));
const About = React.lazy(() => import("./components/About"));
This syntax tells React to load each component dynamically. So, when a user follows a link to the home page, for instance, React only downloads the file for the requested page instead of loading a large bundle file for the entire application.
After the import, we must render the lazy components inside a Suspense component like so:
<Suspense fallback={<p>Loading page...</p>}>
<Route path="/" exact>
<Home />
</Route>
<Route path="/about">
<About />
</Route>
</Suspense>
The Suspense allows us to display a loading text or indicator as a fallback while React waits to render the lazy component in the UI.
3. React.memo
In computing, memoization is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.
In essence, if a child component receives a prop, a memoized component shallowly compares the prop by default and skips re-rendering the child component if the prop hasn’t changed:
import { useState } from "react";
export default function App() {
const [input, setInput] = useState("");
const [count, setCount] = useState(0);
return (
<div>
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
/>
<button onClick={() => setCount(count + 1)}>Increment counter</button>
<h3>Input text: {input}</h3>
<h3>Count: {count}</h3>
<hr />
<ChildComponent count={count} />
</div>
);
}
function ChildComponent({ count }) {
console.log("child component is rendering");
return (
<div>
<h2>This is a child component.</h2>
<h4>Count: {count}</h4>
</div>
);
}
By updating the input field, both the App component and ChildComponent re-render.
Instead, the ChildComponent
should only re-render when clicking the count button because it must update the UI. Here, we can memoize
the ChildComponent
to optimize our app’s performance.
React.memo is a higher-order component used to wrap a purely functional component to prevent re-rendering if the props received in that component never changes:
import React, { useState } from "react";
const ChildComponent = React.memo(function ChildComponent({ count }) {
console.log("child component is rendering");
return (
<div>
<h2>This is a child component.</h2>
<h4>Count: {count}</h4>
</div>
);
});
If the count prop never changes, React will skip rendering the ChildComponent
and reuse the previous rendered result. Hence improving React’s performance.
React.memo()
works pretty well when we pass down primitive values, such as a number in our example. And, if you are familiar with referential equality, primitive values are always referentially equal and return true if values never change.
On the other hand, non-primitive values like object, which include arrays and functions, always return false between re-renders because they point to different spaces in memory.
When we pass down an object, array, or function as a prop, the memoized component always re-renders. Here, we are passing down a function to the child component:
import React, { useState } from "react";
export default function App() {
// ...
const incrementCount = () => setCount(count + 1);
return (
<div>
{/* ... */}
<ChildComponent count={count} onClick={incrementCount} />
</div>
);
}
const ChildComponent = React.memo(function ChildComponent({ count, onClick }) {
console.log("child component is rendering");
return (
<div>
{/* ... */}
<button onClick={onClick}>Increment</button>
{/* ... */}
</div>
);
});
This code focuses on the incrementCount
function passing to the ChildComponent
. When the App component re-renders, even when the count button is not clicked, the function redefines, making the ChildComponent
also re-render.
To prevent the function from always redefining, we will use a useCallback
Hook that returns a memoized version of the callback between renders.
Using the useCallback
Hook
With the useCallback
Hook, the incrementCount
function only redefines when the count dependency array changes:
const incrementCount = React.useCallback(() => setCount(count + 1), [count]);
Using the useMemo
Hook
When the prop we pass down to a child component is an array or object, we can use a useMemo
Hook to memoize the value between renders. As we’ve learned above, these values point to different spaces in memory and are entirely new values.
You can also use the useMemo
Hook to avoid re-computing the same expensive value in a component. It allows us to memoize
these values and only re-compute them if the dependencies change.
Similar to useCallback
, the useMemo
Hook also expects a function and an array of dependencies:
const memoizedValue = React.useMemo(() => {
// return expensive computation
}, []);
Let’s see how to apply the useMemo Hook to improve a React app’s performance. Take a look at the following code that we’ve intentionally delayed to be very slow.
import React, { useState } from "react";
const expensiveFunction = (count) => {
// artificial delay (expensive computation)
for (let i = 0; i < 1000000000; i++) {}
return count * 3;
};
export default function App() {
// ...
const myCount = expensiveFunction(count);
return (
<div>
{/* ... */}
<h3>Count x 3: {myCount}</h3>
<hr />
<ChildComponent count={count} onClick={incrementCount} />
</div>
);
}
const ChildComponent = React.memo(function ChildComponent({ count, onClick }) {
// ...
});
Every time the App component renders, it invokes the expensiveFunction
and slows down the app.
The expensiveFunction
should only be called when the count button is clicked, not when we type in the input field. We can memoize
the returned value of the expensiveFunction
using the useMemo
Hook so that it only re-computes the function only when needed, i.e., when the count button is clicked.
For that, we will have something like this:
const myCount = React.useMemo(() => {
return expensiveFunction(count);
}, [count]);
Optimization techniques come with a cost if not used properly and wrapping everything in memo
or useCallback
won't magically make your apps fast, but using them properly and profiling along the way could be a lifesaver.
4. Windowing or list virtualization in React applications
When you want to render an enormous table or list of data, it can significantly slow down your app’s performance. Virtualization can help in a scenario like this with the help of a library like react-window. react-window helps solve this problem by rendering only the items in the list that are currently visible, which allows for efficiently rendering lists of any size.
5. Lazy loading images in React
To optimize an application that consists of several images, we can avoid rendering all of the images at once to improve the page load time. With lazy loading, we can wait until each of the images is about to appear in the viewport before we render them in the DOM.
Conclusion:
To optimize our React application, we must first find a performance problem in our application to rectify. In this guide, we’ve explained how to measure the performance of a React application and how to optimize the performance for a better user experience.
If you find these techniques helpful do share them with others and also I would love to know of any other techniques, so do comment down below