Languages
[Edit]
EN

React - how to use memo

10 points
Created by:
Dirask Community
2510

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 );

ReactJS

Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - friendly IT community for everyone.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join