
Back
What is React memo?
Andrei T. Ferreira2021-08-31
Requirements
- React.js
Introduction
React is used to optimize performance on you React app, it does that by wrapping components to prevent re-renderings by looking if the props received has changed.
Problem
Let's say you have this component:
import React, { useState } from "react"; const Child = function (props) { // This is re-rendering even without receiving any props return <h1>I'm a child component</h1>; }; export default function App() { const [localState, setLocalState] = useState(0); return ( <div> <Child /> <h1>LocalState: {localState}</h1> <button onClick={() => setLocalState(localState + 1)}> Change local state </button> </div> ); }
As you might expect, by changing local state pressing the , you re-render
component even though no state was passed to it.
Solution
To make your app more efficient you simply wrap the child component with :
import React, { useState, memo } from "react"; const Child = memo(function (props) { // This is rendering once return <h1>I'm a child component</h1>; }); export default function App() { const [localState, setLocalState] = useState(0); return ( <div> <Child /> <h1>LocalState: {localState}</h1> <button onClick={() => setLocalState(localState + 1)}> Change local state </button> </div> ); })
Since the component was not changed or any props was passed, it won't re-render like before.
TLDR
basically memoizes the component wrapped by it, if no props changed.
Additional Resources
Related Posts
- What is React memo?2021-08-31
- What is React's Context API?2021-08-28
ⓒ 2025 Andrei T.F.
with Next.js