React에서 Input lagging을 최소화하는 방법

kiwon kim·2024년 6월 6일

Frontend

목록 보기
4/30

리액트에서 다루는 인풋은 크게 두 가지로 나눌 수 있습니다.

1. Controlled Component ⇒ 여기서 input lagging이 발

  • value, onChange를 이용해서 인풋의 값을 업데이트
import React, { useState } from 'react';

function ControlledComponent() {
  const [value, setValue] = useState('');

  const handleChange = (event) => {
    setValue(event.target.value);
  };

  return (
    <div>
      <label>
        Name:
        <input type="text" value={value} onChange={handleChange} />
      </label>
      <p>The input value is: {value}</p>
    </div>
  );
}

export default ControlledComponent;

2. Uncontrolled Component

  • DOM이 인풋 값을 업데이트하고, 우리는 useRef를 이용해서 인풋의 값에 접근
import React, { useRef } from 'react';

function UncontrolledComponent() {
  const inputRef = useRef();

  const handleSubmit = (event) => {
    alert('A name was submitted: ' + inputRef.current.value);
    event.preventDefault();
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" ref={inputRef} />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
}

export default UncontrolledComponent;

왜 Controlled Component에서는 Input Lagging이 일어나는가?

참고: https://dev.to/kevinkh89/how-to-solve-input-delay-lagging-in-react-j2o

Controlled Component에서는, 모든 키 입력 시 인풋에 영향을 주는 싸이클이 존재한다.

우리가 만약에 상태값을 onChange를 이용해서 변경하면, 리액트는리렌더링을하고, 인풋 value props를 새로운 값으로 변경한다.

이런 싸이클의 과정은 꽤나 비싸며, 이것이 input lagging의 원인!

특히 다음과 같은 경우에는 더 느려질 수 있다.

  1. 복잡한 컴포넌트가 있고, 이 복잡한 컴포넌트 내부의 인풋에 값을 입력 시, 모든 컴포넌트가 리렌더링
  2. 큰 앱이 있는데, 큰 앱의 상태관리(redux, context etc) 등이 모든 키입력에 반응해서 전체앱을 모두 리렌더링 시키는 경

Input Lagging을 해결하는 방법

  1. Controlled Component를 Uncontrolled Component로 변경

  2. Isolated component를 이용 ⇒ 합리적인 대안이 될 수 있다

    1. 인풋의 값을 이용해서 API 호출 시 혹은 redux 값을 변경 시, debounce를 적용하는 것을 권장
    import { debounce } from 'lodash';
    
    // isolated component
    function ControlledInput({ onUpdate }) {
       const [value, setState] = useState();
       const handleChange = e => {
          setState(e.target.value);
          onUpdate(e.target.value);
       };
       return <input value={value} onChange={handleChange} />;
    }
    
    function ComponentB() {
       const input1 = useRef();
       const input2 = useRef();
       const input3 = useRef();
       const handleSubmit = () => {
          //do something with the values
       };
       return (
          <form onSubmit={handleSubmit}>
             <ControlledInput
                onUpdate={val => {
                   input1.current = val;
                   // update global state by debounce ,...
                }}
             />
             ;
             <ControlledInput
                onUpdate={val => {
                   input1.current = val;
                   // update global state by debounce ,...
                }}
             />
             ;
             <ControlledInput
                onUpdate={val => {
                   input1.current = val;
                   //update global state by debounce ,...
                }}
             />
             ;
          </form>
       );
    }

참고

How to solve input delay (lagging) in react

profile
FOR_THE_BEST_DEVELOPER

0개의 댓글