DEV Community

vidhya murali
vidhya murali

Posted on

React Memo

React memo is a Higher Order Component (HOC) introduced in React v16.6. As the name suggests, Memo API uses the memoization technique to optimize performance and make the application faster. The Memo API avoids unnecessary re-renders in functional components thereby optimizing the performance of the application.

Syntax:

const MeomizedComponent = React.memo(function MyAnotherComponent(props) {});

1: Without Using Memo

In this approach we will use a simple form to illustrate component re-rendering works without using React.memo In the Header.js we are simply rendering the Header component with props that displays the props passed from the Parent component.

//App.js
import React, { useState } from "react";
import "./App.css";
import Header from "./Header";
const App = () => {
    console.log("Rendering Form");
    const [name, setName] = useState("");
    return (
        <div className="App">
            <Header title="Input Field" />
            <input
                type="text"
                value={name}
                onChange={(e) => setName(e.target.value)}
            />
        </div>
    );
};
export default App;
Enter fullscreen mode Exit fullscreen mode
//Header.js
import React from "react";
const Header = (props) => {
    console.log("Rendering header");
    return <div>{props.title}</div>;
};
export default Header;
Enter fullscreen mode Exit fullscreen mode

Using Memo

Here, the

component is rendered only once on startup. It is not re-rendered whenever the state changes in the component. Since we are wrapping up the Header component inside the memo, it is not re-rendering the component when the prop doesn’t change.
import React from "react";
const Header = (props) => {
    console.log("Rendering header");
    return <div>{props.title}</div>;
};

// wrapping the component inside memo
export default React.memo(Header);

Reference : https://www.geeksforgeeks.org/reactjs/explain-new-features-of-react-memo-in-react-v16-6/

Top comments (1)

Collapse
 
101beardo profile image
Tarun Sharma

Good intro. One gotcha worth adding, React.memo does a shallow prop comparison, so if you pass an inline arrow function or a new object/array literal as a prop it'll re-render every time anyway since it's a new reference each render. useCallback/useMemo on the parent side is usually what actually makes memo stick.