React
[React] useEffect 초기렌더링시 함수실행 막기
살다보니개발자
2023. 2. 26. 18:25
useEffect 초기렌더링시 함수를 막을려면 아래의 커스텀 훅을 사용하면 된다.
import React, { useEffect, useRef } from 'react';
const useDidMountEffect = (func, deps) => {
const didMount = useRef(false);
useEffect(() => {
if (didMount.current) func();
else didMount.current = true;
}, deps);
}
export default useDidMountEffect;
해당 커스텀훅 사용방법은
import React, { useState, useEffect } from 'react';
import useDidMountEffect from '../path/to/useDidMountEffect';
const MyComponent = (props) => {
const [state, setState] = useState({
key: false
});
useDidMountEffect(() => {
// 'key'가 변경되면 실행. 하지만 초기 렌더링에서는 실행되지 않음.
}, [state.key]);
return (
<div>
...
</div>
);
}
// ...
Make React useEffect hook not run on initial render
According to the docs: componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render. We can use the new useEffect() hook to simulate
stackoverflow.com
태클은 언제나 환영입니다. 잘못된부분이 있으면 댓글남겨주세요 :)