Skip to content

React Memo

Published: at 02:30 AM

Table of contents

Open Table of contents

what is react memo

react memo lets you skip re rendering when props or there is no props in your component are unchanged.

how to know react memo works

i will show you how react memo works. i have example code like this:

App.tsx

import { useState } from 'react'
import './App.css'

const ExpensiveComponent = () => {
  console.log('ini rerender');
  return <div>this is expensive component</div>
}

function App() {
  const [count, setCount] = useState(0);
  const [count2, setCount2] = useState(0);

  return (
    <>
      <div>
        <h2>Count 1</h2>
        <button onClick={() => setCount((count) => count + 1)}>
          count is {count}
        </button>
        <h2>Count 2</h2>
        <button onClick={() => setCount2((count2) => count2 + 1)}>
          count2 is {count2}
        </button>
        <ExpensiveComponent />
      </div>
    </>
  )
}

export default App

in code above, it will re render ExpensiveComponent too even we will click button count 1 or button count 2.

react example

in screenshot above, component ExpensiveComponent always re rendering. how to avoid? we must use memo to avoid that.

App.tsx

import { memo, useState } from 'react'
import './App.css'

const ExpensiveComponent = memo(() => {
  console.log('ini rerender');
  return <div>this is expensive component</div>
})

function App() {
  const [count, setCount] = useState(0);
  const [count2, setCount2] = useState(0);

  return (
    <>
      <div>
        <h2>Count 1</h2>
        <button onClick={() => setCount((count) => count + 1)}>
          count is {count}
        </button>
        <h2>Count 2</h2>
        <button onClick={() => setCount2((count2) => count2 + 1)}>
          count2 is {count2}
        </button>
        <ExpensiveComponent />
      </div>
    </>
  )
}

export default App

in code above, we add memo in component ExpensiveComponent. so even we click button count1 or count2, component ExpensiveComponent not re rendering. react memo example