DEV Community

SATHISHKUMAR R
SATHISHKUMAR R

Posted on

What is React.memo() in React?

React.memo() is a higher-order component (HOC) used to prevent unnecessary re-rendering of functional components.

It re-renders a component only when its props change (using a shallow comparison by default).

  1. Example without React.memo():

import React, { useState } from 'react';

function Child({ name }) {
console.log("Child Component Rendered");

return <h2>Hello {name}</h2>;
Enter fullscreen mode Exit fullscreen mode

}

function App() {
const [count, setCount] = useState(0);

return (
    <div>
        <h1>Count: {count}</h1>

        <button onClick={() => setCount(count + 1)}>
            Increase
        </button>
Enter fullscreen mode Exit fullscreen mode
  1. Example with React.memo():

import React, { useState } from 'react';

const Child = React.memo(({ name }) => {
console.log("Child Component Rendered");

return <h2>Hello {name}</h2>;
Enter fullscreen mode Exit fullscreen mode

});

function App() {
const [count, setCount] = useState(0);

return (
    <div>
        <h1>Count: {count}</h1>

        <button onClick={() => setCount(count + 1)}>
            Increase
        </button>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)