DEV Community

Cover image for "useMemoization" in reactjs
avinashmahlawat
avinashmahlawat

Posted on

"useMemoization" in reactjs

Memoization in React is an optimization technique used to prevent unnecessary re-renders of components or re-calculations of expensive values. It works by caching the result of a function or component based on its inputs (props or dependencies) and returning the cached result if the inputs haven't changed.

1. Memoizing Components with React.memo:
React.memo is a higher-order component (HOC) used to memoize functional components. It prevents the component from re-rendering if its props have not changed.

import React from 'react';

const MyMemoizedComponent = React.memo(({ prop1, prop2 }) => {
  // This component will only re-render if prop1 or prop2 change
  return (
    <div>
      <p>Prop 1: {prop1}</p>
      <p>Prop 2: {prop2}</p>
    </div>
  );
});
Enter fullscreen mode Exit fullscreen mode

2. Memoizing Values with useMemo:
The useMemo hook is used to memoize the result of an expensive calculation. The calculation will only be re-executed if its dependencies change.

import React, { useMemo } from 'react';

function MyComponent({ data }) {
  const expensiveValue = useMemo(() => {
    // Perform an expensive calculation using 'data'
    return data.map(item => item * 2); 
  }, [data]); // Re-calculate only when 'data' changes

  return (
    <div>
      {/* Render expensiveValue */}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

3. Memoizing Callbacks with useCallback:
The useCallback hook is used to memoize a function, preventing it from being re-created on every render. This is particularly useful when passing callbacks as props to memoized child components to avoid unnecessary re-renders of the child.

import React, { useCallback } from 'react';

function ParentComponent() {
  const handleClick = useCallback(() => {
    console.log('Button clicked!');
  }, []); // The function will not be re-created unless dependencies change

  return <ChildComponent onClick={handleClick} />;
}

const ChildComponent = React.memo(({ onClick }) => {
  return <button onClick={onClick}>Click Me</button>;
});
Enter fullscreen mode Exit fullscreen mode

When to Use Memoization:
Expensive calculations:
Memoize the results of computations that are time-consuming or resource-intensive.
Preventing unnecessary re-renders:
Use React.memo for components that receive stable props and whose re-renders are costly.
Optimizing callback functions:
Use useCallback when passing functions as props to memoized child components.

Top comments (0)