반응.메모()

React.memo()는 모든 React 개발자의 무기고에 포함되어야 하는 것 중 하나입니다. React 구성 요소를 기억할 수 있는 기능을 제공합니다. 다른 도구와 마찬가지로 React.memo() 사용 방법에 대해 알아보기 전에 먼저 문제를 해결해 보겠습니다.

메모이제이션이 필요한 이유는 무엇입니까?
메모이제이션은 기본적으로 나중에 사용하기 위해 일부 계산 결과를 캐싱하는 것을 의미하는 일반적인 개념입니다. 이것은 프로그래밍 세계에서 꽤 널리 사용되는 최적화 기술입니다.

메모이제이션을 사용할 때마다 캐시된 결과가 더 이상 유효하지 않고 계산을 다시 수행해야 하는 시기를 결정하는 기준이 있어야 한다는 점을 기억하는 것이 중요합니다.

그것이 해결하는 문제를 이해하려면 다음 React 구성 요소를 고려하십시오.

import { useState, Fragment } from "react";

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

  function handleDecrement() {
    setCount((oldCount) => --oldCount);
  }

  function handleIncrement() {
    setCount((oldCount) => ++oldCount);
  }

  return (
    <Fragment>
      <p>Count is {count}</p>
      <button onClick={handleDecrement}>-</button>
      <button onClick={handleIncrement}>+</button>
    </Fragment>
  );
}

export default App;


늘리거나 줄일 수 있는 항목을 추적하는 간단한 구성 요소입니다.


이제 다른 구성 요소를 <App />에 추가해 보겠습니다. 작업을 더 쉽게 하기 위해 소품으로 전달된 ID msgId에 따라 일종의 메시지를 반환하는 구성 요소<Message />를 생성합니다.

function Message(props) {
  let msg = "hello, world";

  if (props.msgId === 1) {
    msg = "hey there!";
  } else if (props.msgId === 2) {
    msg = "hola!";
  }

  return <p>{msg}</p>;
}


여기에서는 간단하게 유지했지만 이 구성 요소<Message />가 일부 무거운 계산을 수행하거나 최종 메시지를 얻기 위해 외부 API에 요청을 보내는 것을 상상해 보십시오. 믹스에 모든 즐겨찾기console.log()를 추가하여 이 상황을 시뮬레이션합니다.

function Message(props) {
  let msg = "hello, world";

  console.log("Just performed some seriously heavy computation");

  if (props.msgId === 1) {
    msg = "hey there!";
  } else if (props.msgId === 2) {
    msg = "hola!";
  }

  return <p>{msg}</p>;
}

<App />를 사용하도록 구성 요소<Message />를 업데이트해 보겠습니다.

import { useState, Fragment } from "react";

function Message(props) {
  let msg = "hello, world";

  console.log("Just performed some seriously heavy computation");

  if (props.msgId === 1) {
    msg = "hey there!";
  } else if (props.msgId === 2) {
    msg = "hola!";
  }

  return <p>{msg}</p>;
}

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

  function handleDecrement() {
    setCount((oldCount) => --oldCount);
  }

  function handleIncrement() {
    setCount((oldCount) => ++oldCount);
  }

  return (
    <Fragment>
      <Message msgId={1} />
      <p>Count is {count}</p>
      <button onClick={handleDecrement}>-</button>
      <button onClick={handleIncrement}>+</button>
    </Fragment>
  );
}

export default App;



아래 비디오에서 모든 변경 횟수에 대해 무거운 계산이 수행된다는 사실에 특히 주의하십시오.



이 시점에서 한 걸음 물러서서 현재 사용자 인터페이스가 얼마나 비효율적인지 고려하십시오. count는 어떤 식으로든 <Message /> 영향을 미치지 않지만 여전히 count 업데이트할 때마다 매우 무거운 계산이 수행됩니다. 변경msgId으로 인해 다른 메시지가 나타나야 하므로 변경msgId 시에만 계산이 발생하기를 원합니다.

React.memo()가 구조하러 달려갑니다.React.memo() 상위 구성 요소. 구성 요소를 인수로 사용하고 결과를 기억합니다. 메모이제이션된 결과는 원래 구성 요소의 속성이 변경된 경우에만 업데이트됩니다.
React.memo() 를 사용하려면 구성 요소를 인수로 전달하고 결과를 저장하면 됩니다. 구성 요소<Message />는 다음과 같습니다.

import { useState, Fragment, memo } from "react";

const Message = memo(function (props) {
  let msg = "hello, world";

  console.log("Just performed some seriously heavy computation");

  if (props.msgId === 1) {
    msg = "hey there!";
  } else if (props.msgId === 2) {
    msg = "hola!";
  }

  return <p>{msg}</p>;
});


참고: 여기에서 방금 가져왔습니다memo(). React 를 가져온 경우 React.memo() 를 간단히 instead memo() 사용할 수 있습니다.

이제 코드는 다음과 같습니다.

import { useState, Fragment, memo } from "react";

const Message = memo(function (props) {
  let msg = "hello, world";

  console.log("Just performed some seriously heavy computation");

  if (props.msgId === 1) {
    msg = "hey there!";
  } else if (props.msgId === 2) {
    msg = "hola!";
  }

  return <p>{msg}</p>;
});

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

  function handleDecrement() {
    setCount((oldCount) => --oldCount);
  }

  function handleIncrement() {
    setCount((oldCount) => ++oldCount);
  }

  return (
    <Fragment>
      <Message msgId={1} />
      <p>Count is {count}</p>
      <button onClick={handleDecrement}>-</button>
      <button onClick={handleIncrement}>+</button>
    </Fragment>
  );
}

export default App;


이번에는 응용 프로그램이 업데이트될 때 계산이 완료되지만 변경 사항count이 더 이상 이 효과를 나타내지 않는다는 점에 유의하십시오.

좋은 웹페이지 즐겨찾기