ReasonJun

React: Optimizing performance with React.memo & Check performance using React Developer Tools (Chrome Extension) 본문

Frontend/React

React: Optimizing performance with React.memo & Check performance using React Developer Tools (Chrome Extension)

ReasonJun 2023. 6. 13. 13:20
728x90

App.js code :

import { useEffect, useState } from 'react';
import './App.css';
import B from './components/B';
import A from './components/A';

function App() {
  const [value, setValue] = useState('');
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then((res) => res.json())
      .then((posts) => setPosts(posts));
  }, []);

  return (
    <div style={{ padding: '1rem' }}>
      <input value={value} onChange={(e) => setValue(e.target.value)} />
      <div style={{ display: 'flex' }}>
        <A message={value} posts={posts}/>
        <B message={value} posts={posts}/>
      </div>
    </div>
  );
}

export default App;

A Component code :

import React from 'react';

const A = ({ message, posts }) => {

  // Declare all elements in one component
  return (
    <div>
      <h1>A Component</h1>
      <p>{message}</p>
      <ul>
        {posts.map((post) => {
          return (
            <li key={post.id}>
              <p>{post.title}</p>
            </li>
          );
        })}
      </ul>
    </div>
  );
};

export default A;

B Component code :

import React from 'react';

const Message = ({ message }) => {
  return <p>{message}</p>;
};

const ListItem = ({ post }) => {
  return (
    <li key={post.id}>
      <p>{post.title}</p>
    </li>
  );
};

const List = ({ posts }) => {
  return (
    <ul>
      {posts.map((post) => (
        <ListItem post={post} />
      ))}
    </ul>
  );
};

const B = ({ message, posts }) => {
  return (
    <div>
      <h1>B Component</h1>
      <Message message={message} />
      <List posts={posts} />
    </div>
  );
};

export default B;

Looking at above result, the A component comes out much faster.

=> Looking at above result, the A component comes out much faster.

Check which part is rendered when input value is entered through 'Components' of Extension. You can see that the B component is newly created in many parts.

 

In the current app, component B is divided into components B, List, ListItem, and Message. The reason for this division is not only for reusability, but also for optimizing the rendering of each component. For example, when typing text in Input, originally only the Message component and the App component that has its State value should be rendered, but now other unrelated parts are also rendered.

 

Let's try to speed up component B. => use React.memo

 

result :

 

=> The speed is faster than the A component.

728x90
Comments