반응형
리액트 훅: 사용 중인 첫 번째 실행 건너뛰기 효과
첫 번째 실행을 건너뛰는 방법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
반응형
'programing' 카테고리의 다른 글
React Native 스타일링의 구성요소 간 간격 (0) | 2023.03.29 |
---|---|
PHP 팩터 30 Linux와 Windows의 성능 차이 (0) | 2023.03.29 |
Spring Boot 버전을 2.0.3에서 변경할 때 문제가 발생합니다.릴리스 2.1.0.빌드 스냅샷 (0) | 2023.03.29 |
MongoDb 합계 쿼리 (0) | 2023.03.29 |
TypeScript에서 Enum like type을 생성하는 방법 (0) | 2023.03.29 |