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.
