React memoization
Created By: chatGPT
Memoization in React is a performance optimization technique that helps avoid unnecessary re-renders of components. It memorizes the result of expensive function calls and returns the cached result when the same inputs occur again. This can significantly improve the performance of your React applications, especially when dealing with heavy computations or when the component has many props. React provides a hook called
useMemo
and a higher-order component called React.memo
to enable memoization.import React, { useMemo } from 'react';
const ExpensiveComputation = ({ number }) => {
const computeFactorial = (n) => {
console.log('Computing factorial...');
return n <= 0 ? 1 : n * computeFactorial(n - 1);
};
const factorial = useMemo(() => computeFactorial(number), [number]);
return <div>Factorial of {number} is {factorial}</div>;
};
const App = () => {
const [count, setCount] = React.useState(0);
const [number, setNumber] = React.useState(5);
return (
<div>
<ExpensiveComputation number={number} />
<button onClick={() => setCount(count + 1)}>Count: {count}</button>
<button onClick={() => setNumber(number + 1)}>Next Number</button>
</div>
);
};
export default App;
Using
It’s important to note that memoization should be used wisely. Overusing it can lead to complexity and memory issues. Always analyze performance bottlenecks before applying memoization techniques.React.memo
, you can memoize your functional components to avoid re-rendering if the props haven't changed. This is similar to how PureComponent
works, but for functional components.const MyComponent = React.memo(({ name }) => {
console.log('Rendering:', name);
return <div>{name}</div>;
});
const ParentComponent = () => {
const [count, setCount] = React.useState(0);
const [name, setName] = React.useState('Alice');
return (
<div>
<MyComponent name={name} />
<button onClick={() => setCount(count + 1)}>Count: {count}</button>
<button onClick={() => setName(name === 'Alice' ? 'Bob' : 'Alice')}>Toggle Name</button>
</div>
);
};
export default ParentComponent;