NashTech Blog

Optimize Your React App By Stop Re-Rendering Components: Recat memo() Hook

Table of Contents
memo

React is a library that allows us to create single-page applications. As we all know, on change, any state value in React will re-render the component and update the state and view of the component. If we think logically, the functionality provided by React is great as it updates the view at instance, but when we use compoent in our component, then it looks like a mess as it re-renders all components from parent to child. To solve this issue, React provides us a hook that helps us to determine whether we need to re-render the component or not.

memo() React Hook

memo(): A hook that re-renders the components when it’s props are changed or skips re-rendering when their props are unchanged.

To learn more related to React, check this link.

React normally re-renders a component whenever its parent re-renders. With memo, you can create a component that React will not re-render when its parent re-renders so long as its new props are the same as the old props. Such a component is said to be memoized.

Let’s understand it by example

import { memo, useState } from 'react';

export default function MyApp() {
 const [name, setName] = useState('');
  return (
    <>
      <Header />
     <label>
        Name{': '}
        <input value={name} onChange={e => setName(e.target.value)} />
      </label>
    </>
  );
}

const Header = memo(function Header(}) {
  console.log("Header was rendered at", new Date().toLocaleTimeString());
  return ( 
<header>
   <h1>React Header</h1>
</header> )
});

In the above code, we have the header component, which is memorised by memo Hook. The header component does not depend on the parent component. On change of parent component state header component will not re-render.

The component will re-render only when it’s dependent on the parent or it’s own state will update.

Here is the other example of how memo works really.

In this example, we will re-render the child component on changing parent state change.

import { memo, useState } from 'react'

function App() {
  const [name, setName]= useState('');
  return (
    <div className="App">
      <label>
        <input type='text' onChange={(event)=> setName(event.target.value)} />
      </label>
      <Header />
      <GreetingCompoenent  name={name}/>
    </div>
  );
}


const Header  = memo(function Header() {
  console.log("Header re-rendering")
    return (
        <header>
            <h1> React Header</h1>
        </header>
    )
})


const GreetingCompoenent = memo(({name})=>{
  console.log(name)
  return <p>`Greeting from ${name}`</p>
})


export default App;

In the above code, you can simply understand that the GreetingComponent depends on the parent component, so on updating the parent state, the child component is updating( Greeting Component) but it’s clearly visible that the Header component renders only once as it’s memorised in the memo hook.

For more, you can read here memo() Hook.

Conclusion

Optimising your application is one of the most heated topics. In today’s fast-growing single-page application world, minimising the re-rendering and reduing dom manipulation is very important. By using memo in React applications, we can reduce unnecessary re-render/code execution.

However, like any optimization tool, memo should be used judiciously. Overusing it or applying it unnecessarily can lead to more complexity without noticeable performance gains. It’s essential to profile your application to identify bottlenecks before deciding to use useMemo.

In summary, memo is best suited for:

  • Avoiding redundant rendering.
  • Enhancing performance in components with expensive calculations and rendering all child components.

By understanding when, where, and how to use memo, you can create more efficient and responsive React applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

Scroll to Top