리액트에서 다루는 인풋은 크게 두 가지로 나눌 수 있습니다.
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;
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;
참고: https://dev.to/kevinkh89/how-to-solve-input-delay-lagging-in-react-j2o
Controlled Component에서는, 모든 키 입력 시 인풋에 영향을 주는 싸이클이 존재한다.
우리가 만약에 상태값을 onChange를 이용해서 변경하면, 리액트는리렌더링을하고, 인풋 value props를 새로운 값으로 변경한다.
이런 싸이클의 과정은 꽤나 비싸며, 이것이 input lagging의 원인!
특히 다음과 같은 경우에는 더 느려질 수 있다.
Controlled Component를 Uncontrolled Component로 변경
Isolated component를 이용 ⇒ 합리적인 대안이 될 수 있다
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>
);
}
참고