# 28) React.memo

1.  **<mark class="bg-yellow-200 dark:bg-yellow-500/30">What is React.memo</mark>**  
    React.memo is a higher-order component that prevents unnecessary re-renders by memoizing a functional component and re-rendering it only when its props change.  
    `React.memo` is a performance optimization in React that **prevents unnecessary re-renders of functional components**.  
    React.memo is a higher-order component (HOC) that,  
    i) **memoizes** a component  
    ii) re-renders it **only when its props change**
    
2.  **<mark class="bg-yellow-200 dark:bg-yellow-500/30">Problem Without React.memo</mark>**
    
    ```javascript
    const Child = (props) => {
      console.log("Child Rendered");
      return <h2>{props.name}</h2>;
    }
    
    const Parent = () => {
      const [count, setCount] = useState(0);
    
      return (
        <>
          <Child name="Rahul" />
          <button onClick={() => setCount(count + 1)}>
            Count: {count}
          </button>
        </>
      );
    }
    ```
    
    Here, When you click on button,  
    Parent component will get re-renders, also the Child component gets re-renders (even though props didn’t change).
    
3.  **<mark class="bg-yellow-200 dark:bg-yellow-500/30">Solution: React.memo</mark>**
    
    ```javascript
    const Child = React.memo((props) => {
      console.log("Child Rendered");
      return <h2>{props.name}</h2>;
    });
    ```
    
    Here, When you click on button,  
    Parent component will get re-renders but due to React.memo the Child re-renders ONLY if name props gets changed.
    
4.  **<mark class="bg-yellow-200 dark:bg-yellow-500/30">How React.memo Works</mark>**  
    Performs shallow comparison of props  
    If props are equal → skips rendering  
    If props change → re-renders  
      
    Use it when,  
    i) Component re-renders frequently  
    ii) Props rarely change  
    iii) Rendering is expensive  
    Avoid when,  
    i) Component is small/simple  
    ii) Props change often  
    iii) Adds unnecessary complexity
    
5.  **<mark class="bg-yellow-200 dark:bg-yellow-500/30">React.memo vs useMemo vs useCallback</mark>**  
    **i) What it memoizes**  
    React.memo - Component  
    useMemo - Value  
    useCallback - Function  
    **ii) Use case**  
    React.memo - Prevent re-render  
    useMemo - Cache result  
    useCallback - Stable function reference
    
6.  **<mark class="bg-yellow-200 dark:bg-yellow-500/30">Key Benefits</mark>**  
    i) Improves performance  
    ii) Reduces unnecessary renders  
    iii) Optimizes large applications
