Languages
[Edit]
EN

React - how to use memo

10 points
Created by:
Gigadude
791

In this article we would like show you how to use memo function in React.

Note: React.memo() guarantees that a component will be re-rendered only if props are changed for the component - it is used to boost performance of a application.

Below example shows two functional components - NormalComponent and MemoComponent.
The MemoComponent was created with React.memo(), which means React renders component only on the MemoComponent props change - in our case it doesn't have props, so it will be rendered only once at begining.

In the example we set a counter to display how many times each element was rendered.

Runnable example:

// ONLINE-RUNNER:browser;

//Note: Uncomment import lines during working with JSX Compiler.
// import React from react';

const NormalComponent = () => {
	const counterRef = React.useRef(0);
	console.log(`--- [Normal Component] rendering: counter=${++counterRef.current}`);
	return <div>[Normal Component]</div>;
};

const MemoComponent = React.memo(() => {
	const counterRef = React.useRef(0);
	console.log(`--- [Memo Component] rendering: counter=${++counterRef.current}`);
	return <div>[Memo Component]</div>;
});

const App = () => {
	const [counter, setCounter] = React.useState(1);
	console.log(`- [App] rendering: counter=${counter}`);
	return (
	  <div>
		<NormalComponent />
		<MemoComponent />
		<button onClick={() => setCounter(counter + 1)}>Click me!</button>
	  </div>
	);
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

Alternative titles

  1. React - memo example
  2. React - how to reduce big amount of re-rendering in function components
  3. React - how memo works
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - how to use memo
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join