ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 1-15 throttling & debouncing (2)
    React 심화주차 2023. 5. 17. 16:54

    이벤트핸들러 사용하고 다른 페이지로 가도 throttling & debouncing이 실행되는 데이터 누수를 막기위한
    방법을 알아보자.

     yarn add lodash
    import _ from "lodash"
    
    import { useState } from "react";
    import "./App.css";
    import _ from "lodash";
    import { useCallback } from "react";
    
    function App() {
      const [searchText, setSearchText] = useState("");
      const [inputText, setInputText] = useState("");
    
      const handleSearchText = useCallback(
        _.debounce((text) => {
          setSearchText(text);
        }, 2000),
        []
      );
      //공통함수
      const handleChange = (e) => {
        setInputText(e.target.value);
        handleSearchText(e.target.value);
      };
    
      return (
        <div
          style={{
            paddingLeft: "20px",
            paddingRight: "20px",
          }}
        >
          <h1>디바운싱 예제</h1>
          <input
            placeholder="입력값을 넣고 디바운싱 테스트를 해보세요"
            style={{ width: "300px" }}
            type="text"
            onChange={handleChange}
          />
          <p>Search Text : {searchText}</p>
          <p>Input Text : {inputText}</p>
        </div>
      );
    }
    
    export default App;



    만들어져있는 라이브러리를 통해 방법을 알아보자(Lodash).

    import { useState } from "react";
    import "./App.css";
    import _ from "lodash";
    import { useCallback } from "react";
    
    function App() {
      const [searchText, setSearchText] = useState("");
      const [inputText, setInputText] = useState("");
    
      const debounce = (callback, delay) => {
        let timerId = null;
        return (...args) => {
          if (timerId) clearTimeout(timerId);
          timerId = setTimeout(() => {
            callback(...args);
          }, [delay]);
        };
      };
    
      const handleSearchText = useCallback(
        debounce((text) => {
          setSearchText(text);
        }, 2000),
        []
      );
    
      //공통함수
      const handleChange = (e) => {
        setInputText(e.target.value);
        handleSearchText(e.target.value);
      };
    
      return (
        <div
          style={{
            paddingLeft: "20px",
            paddingRight: "20px",
          }}
        >
          <h1>디바운싱 예제</h1>
          <input
            placeholder="입력값을 넣고 디바운싱 테스트를 해보세요"
            style={{ width: "300px" }}
            type="text"
            onChange={handleChange}
          />
          <p>Search Text : {searchText}</p>
          <p>Input Text : {inputText}</p>
        </div>
      );
    }
    
    export default App;

    Search Text는useEffect를 통해 메모이제이션 되었다가 2초 후에 잘 반영되는것을 볼 수 있다.

    'React 심화주차' 카테고리의 다른 글

    1-17 인증/인가 (세션)  (0) 2023.05.17
    1-16 인증/인가 (쿠키)  (0) 2023.05.17
    1-14 throttling&debouncing (1)  (0) 2023.05.17
    1-13 react query (2)  (0) 2023.05.17
    1-12 react query (1)  (0) 2023.05.17
Designed by Tistory.