programing

리액트 훅: 사용 중인 첫 번째 실행 건너뛰기 효과

cafebook 2023. 3. 29. 21:54
반응형

리액트 훅: 사용 중인 첫 번째 실행 건너뛰기 효과

첫 번째 실행을 건너뛰는 방법useEffect갈고리를 채우다

useEffect(() => {
    const first = // ???
  if (first) {
    // skip
  } else {
    // run main code
  }
}, [id]);

후크는 모든 가변값을 저장하기 위해 사용할 수 있으므로 효과를 처음 실행하는지 여부를 나타내는 부울을 저장할 수 있습니다.

const { useState, useRef, useEffect } = React;

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

  const isFirstRun = useRef(true);
  useEffect (() => {
    if (isFirstRun.current) {
      isFirstRun.current = false;
      return;
    }

    console.log("Effect was run");
  });

  return (
    <div>
      <p>Clicked {count} times</p>
      <button
        onClick={() => {
          setCount(count + 1);
        }}
      >
        Click Me
      </button>
    </div>
  );
}

ReactDOM.render(
  <MyComponent/>,
  document.getElementById("app")
);
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

<div id="app"></div>

언급URL : https://stackoverflow.com/questions/53351517/react-hooks-skip-first-run-in-useeffect

반응형