
Memo in ReactJS
β Memo in ReactJS
In ReactJS, React.memo()
is a higher-order component (HOC) used to optimize functional components by preventing unnecessary re-renders. It memoizes (remembers) the result of a component and re-renders it only if its props change.
π Why Use React.memo()?
Prevents Unnecessary Re-Renders: If a component receives the same props, it wonβt re-render.
Improves Performance: Especially useful for large applications with complex UI.
Efficient State Management: Reduces resource consumption by optimizing component rendering.
π Syntax
<h1>{value}<div> import React, { useState } from 'react';const Child = React.memo(({ value }) => { <h1>{value}<div> import React, { useState, useCallback } from 'react';const Child = React.memo(({ onClick }) => { <button <div> <p>Count: {count}</p> <Child onClick={handleClick} /> <button onClick={() => setCount(count + 1)}>Increment</button> </div> );};export default App;
π Explanation:
useCallback() β Memoizes the function to prevent unnecessary renders.
React.memo() β Ensures the
Child
component does not re-render when the parent re-renders.
π When to Use React.memo()?
Components that receive the same props frequently.
Large lists or grids with numerous child components.
Components performing complex calculations or data manipulations.
Components that don't rely on global state changes.
π When Not to Use React.memo()?
Components that already re-render very quickly.
Components that frequently change state or props.
Components that rely on context or use React hooks without optimizations.
β Final Thoughts
Use
React.memo()
to prevent unnecessary renders.Combine it with
useCallback
for function memoization.Always check the componentβs performance before using
React.memo()
.