In React, the memo
function is a higher-order component that improves performance by preventing re-renders of a component when its props haven’t changed. It can be particularly useful in complex applications where frequent re-renders may lead to performance issues.
The Problem: Unnecessary Re-Renders
By default, React re-renders a component whenever its parent component re-renders, even if the props passed to it haven’t changed.
Here’s an example where a Todos
component re-renders unnecessarily:
Code Example:
index.js
// index.js
import { useState } from "react";
import ReactDOM from "react-dom/client";
import Todos from "./Todos";
function App() {
const [count, setCount] = useState(0);
const [todos, setTodos] = useState(["Task 1", "Task 2"]);
const increment = () => {
setCount((prevCount) => prevCount + 1);
};
return (
<>
<Todos todos={todos} />
<hr />
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
</>
);
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
Todos.js
// Todos.js
function Todos({ todos }) {
console.log("Todos component rendered!");
return (
<>
<h2>Todo List</h2>
{todos.map((todo, index) => (
<p key={index}>{todo}</p>
))}
</>
);
}
export default Todos;
When you click the Increment button, the Todos
component re-renders unnecessarily even though the todos
data remains unchanged.
The Solution: Using memo
React’s memo
helps to optimise this behaviour by preventing the Todos
component from re-rendering unless its props
actually change.
To use memo
, simply wrap the Todos
component during export.
Updated Code Example:
Todos.js
// Todos.js
import React, { memo } from "react";
function Todos({ todos }) {
console.log("Todos component rendered!");
return (
<>
<h2>Todo List</h2>
{todos.map((todo, index) => (
<p key={index}>{todo}</p>
))}
</>
);
}
export default memo(Todos);
With this change, the Todos
component will only re-render when the todos
prop updates.
How It Works #
- Without
memo
: TheTodos
component re-renders whenever the parent component (App
) re-renders, regardless of whether thetodos
prop changes. - With
memo
: React skips rendering theTodos
component if itsprops
haven’t changed, reducing unnecessary processing.
Practical Usage #
Use memo
for:
- Components that render the same output for the same props.
- Performance-critical applications where avoiding unnecessary rendering is crucial.
By using memo
, you can significantly optimise performance in large-scale React applications by minimising redundant renders. Try it in your project and notice the difference!
Want to learn React with an instructor, either offline or online? Find experienced tutors near you and join Coaching Wallah—completely free for students!
Leave your comment