Understanding Memoization in react

Understanding Memoization in React

Understanding Memoization in React

Hello, fellow coders! 👋 Today, we're diving into an exciting topic: Memoization in React. Memoization is a powerful technique that helps improve the performance of your React applications by preventing unnecessary re-renders. Let's break it down!

What is Memoization?

Memoization is a form of caching that stores the results of expensive function calls and returns the cached result when the same inputs occur again. In React, memoization can help optimize your components.

Using React.memo

The React.memo higher-order component is used to memoize functional components. It only re-renders the component if its props change.


import React from 'react';

const MyComponent = React.memo(({ data }) => {
  console.log('Rendering MyComponent');
  return <div>{data}</div>;
});

export default MyComponent;

    

Using useMemo

The useMemo hook memoizes a value, recomputing it only when its dependencies change. This is useful for expensive calculations.


import React, { useMemo } from 'react';

const MyComponent = ({ items }) => {
  const expensiveCalculation = useMemo(() => {
    console.log('Running expensive calculation');
    return items.reduce((acc, item) => acc + item, 0);
  }, [items]);

  return <div>{expensiveCalculation}</div>;
};

export default MyComponent;

    

Using useCallback

The useCallback hook memoizes a function, ensuring it only changes if its dependencies change. This is useful for stable callbacks.


import React, { useCallback, useState } from 'react';

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

  const handleClick = useCallback(() => {
    console.log('Button clicked');
    setCount((prevCount) => prevCount + 1);
  }, []);

  return <button onClick={handleClick}>Click me</button>;
};

export default MyComponent;

    

Combining Techniques

Here’s an example combining React.memo, useMemo, and useCallback to optimize a component:


import React, { useState, useMemo, useCallback } from 'react';

const ExpensiveComponent = React.memo(({ items }) => {
  const total = useMemo(() => {
    console.log('Calculating total');
    return items.reduce((acc, item) => acc + item, 0);
  }, [items]);

  return <div>Total: {total}</div>;
});

const MyComponent = () => {
  const [items, setItems] = useState([1, 2, 3, 4]);
  const [count, setCount] = useState(0);

  const addItem = useCallback(() => {
    setItems((prevItems) => [...prevItems, Math.random()]);
  }, []);

  return (
    <div>
      <ExpensiveComponent items={items} />
      <button onClick={addItem}>Add Item</button>
      <button onClick={() => setCount(count + 1)}>Re-render</button>
    </div>
  );
};

export default MyComponent;

    

Happy coding! 🚀

Comments

Popular Posts