🛠️ 처음부터 만드는 Once — 함수를 한 번만 실행하기
문제
초기화 로직, API 호출, 이벤트 리스너 등에서 함수를 정확히 한 번만 실행해야 할 때가 있다. 실수로 여러 번 호출해도 처음 실행만 사용하려면?
기본 구현
```javascript
function once(fn) {
let called = false;
let result;
return function(...args) {
if (!called) {
called = true;
result = fn.apply(this, args);
}
return result;
};
}
// 사용 예
const init = once(() => {
console.log('초기화됨');
return true;
});
init(); // "초기화됨" → true
init(); // 실행 안 됨 → true (이전 결과 반환)
```
핵심 개념
실무 패턴
```javascript
// React 훅에서
const setupOnce = once(() => {
document.addEventListener('DOMContentLoaded', handler);
});
// 여러 컴포넌트가 호출해도 리스너 1개만 등록
setupOnce();
setupOnce();
```
주의사항
공식 문서: [Lodash once](https://lodash.com/docs/#once)
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!