리팩토링을 진행하면서 forEach문을 reduce함수를 이용하여 수정하였다.
저번에 reduce함수에 대해서 다뤘으니 이번 글에서는 예시문만 작성해보려고 한다.
useEffect(() => {
const buttons = wrapElement.querySelectorAll('button');
let totalButtonWidth = 0;
buttons.forEach((button) => {
const buttonStyles = getComputedStyle(button);
const buttonWidth = button.offsetWidth + parseFloat(buttonStyles.marginLeft);
totalButtonWidth += buttonWidth;
});
}, []);
이게 얼마나 바보같은 코드인가...
useRef와 reduce를 이용하면 가독성도 좋고 성능도 좋아질텐데!!
reduce
함수로 배열의 합을 구하게 되면 요소를 하나씩 순회하면서 누적값을 계산하는 방식으로 작동하는데 forEach
문은 배열을 순회하며서 요소를 처리하는 로직과 누적값을 계산하는 로직이 분리되기 때문에 코드가 더 복잡해진다.
그리고 reduce
함수는 초기값을 설정하며 하나의 결과값을 반환하지만 forEach
문은 초기값 설정이 불가능 하며 반환값이 없고 순회하며 동작을 하는 데 사용된다.
const selectedTabArrayRef = useRef<HTMLButtonElement[] | null[]>([]);
useEffect(() => {
if (!selectedTabArrayRef.current?.length) return;
const totalButtonWidth = [...selectedTabArrayRef.current].reduce((acc, cur) => {
const getMarginLeft = (cur && getComputedStyle(cur).marginLeft) ?? '';
return cur ? acc + cur.offsetWidth + parseFloat(getMarginLeft) : acc;
}, 0);
}, []);
출력되는 값과 현재 요소를 구해서 더하면 끝!
의존성 배열에는 맞는 data를 넣으면 될 것 같다.
좀 더 쉽게 풀어서 설명하자면 아래와 같이 설명할 수 있다.
const arr = [1, 2, 3, 4, 5];
let sum = 0;
arr.forEach((item) => {
sum += item;
});
console.log(sum); // 출력 결과: 15
const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(sum); // 출력 결과: 15
리팩토링하는 능력을 기르자!