TIL-41 React 함수 재활용 ♻️

PRB·2021년 9월 28일
0

React

목록 보기
10/22
post-thumbnail

1. 재사용 가능한 함수

// App.js
fetch("http://localhost:8000/products/1")

위 함수는 http://localhost:8000/products/1 주소에 대하여 데이터를 호출하는 로직이다. 이 로직을 한번만 사용한다면 크게 상관없지만, 데이터를 받아오는 로직이 수십 군데로 늘어났을 경우에는 유지보수가 힘들어진다.(
만약 백엔드 API 주소가 달라질 경우 모든 fetch 함수 안에 작성된 url 주소를 하나하나 찾아다니면서 수정해주어야 한다는 뜻)

// src/config.js
export const API = "http://localhost:8000";

// App.js
fetch(`${API}/product/1`);

위와 같이 반복되는 상수들을 별도 파일로 분리하여 관리하는 것만으로도 한 군데만 바꾸더라도 모든 주소를 동일하게, 안전하게 수정할 수 있게 된다.

// DON'T
const fourRuleCalculate = (event, a, b) => {
	const { innerText } = event.target;
	
	if (innerText === "+") {
		return a + b
	} else if (innerText === "-") {
		return a - b
	} else if (innerText === "*") {
		return a * b
	} else if (innerText === "/") {
		return a / b
	}
}

// DO
const sum = (a, b) => a + b
const minus = (a, b) => a - b
const multiply = (a, b) => a * b
const divide = (a, b) => a / b
// DON'T
width = container > 960 ? (growWithContainer ? (container * 0.8) : 960) : container;

// DO
if (container > 960) {
  if (growWithContainer) {
    width = container * 0.8;
  } else {
    width = 960;
  }
} else {
  width = container;
}
profile
사용자 입장에서 사용자가 원하는 것을 개발하는 프론트엔드 개발자입니다.

0개의 댓글