To achieve optimizing components with memoization in React, you can analyze the application and identify components that re-render frequently, even when their props remain unchanged. These components are good candidates for optimization. By memoizing functional components you can improve the performance of your React applications by minimizing unnecessary re-renders and optimizing rendering performance.
React provides the memo()
function to memoize the component and prevent unnecessary re-renders when its props remain the same. The memo()
function lets you skip re-rendering a component when its props are unchanged.
How it works
To memoize a functional component, simply wrap it with the memo()
function. When a component wrapped with the memo()
function receives new props, React will compare the new props with the previous props. If the props haven’t changed, the memo()
function will return the cached result, preventing the component from re-rendering unnecessarily.
Example of the memoized component
Footer.tsx
import { memo } from "react";
function Component({ user }: { user: string }) {
return (
<>
<h2>Footer component</h2>
<div>{user}</div>
</>
);
}
const Footer = memo(Component);
export default Footer;
Testing memoization
To test the memoized Footer
component, we want to verify that it re-renders only when necessary, based on changes to its props.
Main.tsx
import { useState } from "react";
import Footer from "./Footer";
export default function Main() {
const [user, setUser] = useState<string>("Unknown");
const [refresh, setRefresh] = useState<boolean>(false);
return (
<div>
<main>
<h1>Main component</h1>
<button onClick={() => setUser("Unknown")}>Set Unknown</button>
<button onClick={() => setUser("Matej")}>Set Matej</button>
<button onClick={() => setRefresh(true)}>Set refresh true</button>
<button onClick={() => setRefresh(false)}>Set refresh false</button>
</main>
<footer>
<Footer user={user} />
</footer>
</div>
);
}
Changing the user value
setUser()
updates the Main
component user state to the new value. This state change triggers a re-render of the Main
component. The Footer
component, as a child of the Main
component, receives the new user
prop from the updated state. Since the prop passed to the Footer
component has changed, the React memoization mechanism detects the change. As a result, the memoized Footer
component re-renders with the updated user
prop.
Changing the refresh value
setRefresh()
updates the Main
component refresh state to the new value. The user
value remains unchanged. The change in the refresh state triggers a re-render of the Main
component. Since the Footer
component is a child of the Main
component, it receives the unchanged user prop from the state. Because the Footer
component was memoized using memo()
function, it only re-renders when its props (in this case, user
) change. It avoids unnecessary re-renders when the refresh state changes, which improves rendering efficiency.