반응형
SMALL
function useEffect(callback, dependencies) {
const previousDependencies = useRef(dependencies);
// Call the callback function if dependencies have changed
if (!areDependenciesEqual(previousDependencies.current, dependencies)) {
callback();
}
// Update the previous dependencies
// useRef를 이용해서 이전 값을 기억하기 때문에
// previousDependencies가 바뀌어도 리렌더링 되지 않습니다.
previousDependencies.current = dependencies;
}
// 두 deps array가 같은지 체크하는 Helper function
// arr1은 이전 deps array
// arr2는 현재 deps array
function areDependenciesEqual(arr1, arr2) {
// deps array가 아예없거나
// 이전 deps array와 현재 deps array가 같다면
// 위의 callback function을 트리거한다
if (arr1 === undefined || arr2 === undefined || arr1.length !== arr2.length) {
return false;
}
// 이전 deps arr[i]와 현재 deps arr[i]가 하나라도 다르다면
// 위의 callback function을 트리거한다
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
// 이게 다 아닐경우
// 위의 callback function을 트리거하지 않는다
return true;
}
반응형
LIST
'React' 카테고리의 다른 글
리액트에서 몇 초 간격으로 Polling 하는 로직을 만들 때 유의할 점(Feat. 타이머) (0) | 2023.03.14 |
---|---|
React의 StrictMode는 컴포넌트를 리렌더링하게 만드는건가? (0) | 2023.03.09 |
React에서 useEffect 대신에 useLayoutEffect가 더 좋을까? (0) | 2023.03.09 |
react-hook-form + @testing-library/react + Jest 어떻게 테스트 하지? (0) | 2023.03.01 |
Jest + Testing Library +React에서 scrollTo is not a function 에러를 마주쳤을 때? (0) | 2023.03.01 |