프레임워크/React
[React/lodash] React에서 debounce 간단 사용방법
D.Y
2020. 3. 31. 10:19
안녕하세요.
오늘은 lodash의 debounce 메소드에 대해서 알아보도록 하겠습니다.
debounce란?
- 특정 이벤트가 발생할때 작동하는 비즈니스 로직이 과도하게 발생하는 것을 방지하기위해 사용되는 함수이다.
- input box에서 검색어를 입력할때마다 서버에서 연관된 검색어 정보를 가져와 보여주는 기능을 구현할때 주로 사용한다.
- 마지막 이벤트가 호출된 이후에 일정시간이 지난 후에 함수를 지연호출 시키는 역할을 한다.
Sample Code
샘플 코드는 여기에서 다운로드 받으실 수 있습니다. :)
import React from "react";
import "./App.css";
import { debounce } from "lodash";
const somthingFunc = () => {
console.log("called somthingFunc");
};
const debounceSomethingFunc = debounce(() => {
console.log("called debounceSomethingFunc");
}, 200);
function App() {
const [text, setText] = React.useState("");
const [text2, setText2] = React.useState("");
const onChange = event => {
const value = event.target.value;
setText(value);
somthingFunc();
};
const onDebounceChange = event => {
const value = event.target.value;
setText2(value);
debounceSomethingFunc();
};
return (
< div className="App">
< div>
< label>
< span style={{ marginRight: 16 }}>텍스트1< /span>
< input type="text" value={text} onChange={onChange} />
< /label>
< /div>
< div>
< label>
< span style={{ marginRight: 16 }}>텍스트2< /span>
< input type="text" value={text2} onChange={onDebounceChange} />
< /label>
< /div>
< div style={{ marginTop: 16 }}>console을 확인해주세요.< /div>
< /div>
);
}
export default App;
실행 결과
참조
https://github.com/leeduyoung/ReactSample/tree/master/react-lodash
https://lodash.com/docs/4.17.15#debounce
https://hyunseob.github.io/2016/04/24/throttle-and-debounce/