An explanation of React.memo and its uses.
Join DevzConnect โ where devs connect, code, and level up together. Got questions? Stuck on a bug? Or just wanna help others crush it? Jump in and be part of a community that gets it
Welcome back to DevzConnect โ where devs connect, code, and level up together. Ready to pick up where you left off? Dive back in, ask questions, share wins, or help others crush their goals!
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
What is
React.memo
?React.memo
is a Higher-Order Component (HOC) in React that memoizes functional components, preventing unnecessary re-renders when props haven’t changed.PureComponent
but for functional components.๐ ๏ธ Basic Syntax:
const MemoizedComponent = React.memo(MyComponent);
MyComponent
will only re-render if its props change.๐งฉ Example Without
React.memo
(Unnecessary Re-renders):๐ Issue:
Child
re-rendersโeven though itsname
prop hasn’t changed.โ Optimized with
React.memo
:๐ What Changed?
React.memo
wraps theChild
component.Child
only re-renders if thename
prop changes.Child
.โก When to Use
React.memo
?โ ๏ธ When NOT to Use
React.memo
?๐ง Advanced: Using
React.memo
withareEqual
FunctionTo control re-renders more precisely, pass a custom comparison function.
Here,
Child
will only re-render if theuser.id
changes, ignoring changes in other properties.๐ Pro Tip:
React.memo
withuseMemo
oruseCallback
for props that are functions or objects to avoid reference changes.React.memo
can lead to premature optimizations.