HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

React Memo

React Memo

Using memo will cause React to skip rendering a component if its props have not changed.

This can improve performance.

Here's how you can use 'React.memo':

import React from 'react';

const MyComponent = React.memo(({ prop1, prop2 }) => {
// Component logic

return (
<div>
{/* JSX content */}
</div>
);
});

With 'React.memo', the component will only re-render if its props have changed. It performs a shallow comparison of the props to determine whether the component should update.

When to Use React.memo:

1.Pure Functional Components:
  • Use 'React.memo' when you have pure functional components that solely depend on their props and don't have internal state.
  • 2.Optimizing Re-renders:
  • Use 'React.memo' when you want to optimize performance by preventing unnecessary re-renders of components with the same props.
  • import React, { useState } from 'react';

    const Counter = React.memo(({ count, onClick }) => {
    console.log("Render Counter");
    return (
    <div>
    <p>Count: {count}</p>
    <button onClick={onClick}>Increment</button>
    </div>
    );
    });

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

    const handleIncrement = () => {
    setCount(count + 1);
    };

    return (
    <div>
    <Counter count={count} onClick={handleIncrement} />
    </div>
    );
    };

    export default App;