Front-end/React

controlled & uncontrolled input

c62 2023. 2. 2. 17:44
setState를 사용하면 안된다
ref는 나쁘다
로 두가지 모순되는 의견들이 있다

Uncontrolled


uncontrolled(비제어) input은 전통적인 HTML form input이다
class Form extends Component {
  handleSubmitClick = () => {
    const name = this._name.value;
    // do something with `name`
  };

  render() {
    return (
      <div>
        <input type="text" ref={(input) => (this._name = input)} />
        <button onClick={this.handleSubmitClick}>Sign up</button>
      </div>
    );
  }
}
  • 위와 같은경우 ref를 통해 해당 component의 value를 가져올 수 있다.(pull value)
  • form 이 submit 되는 경우 일어날 수 있다

 

 

Controlled


controlled(제어) Input 은 현재 value를 prop으로 받고 해당 값을 변경하기 위한 callback도 받음
class Form extends Component {
  constructor() {
    super();
    this.state = {
      name: "",
    };
  }

  handleNameChange = (event) => {
    this.setState({ name: event.target.value });
  };

  render() {
    return (
      <div>
        <input type="text" value={this.state.name} onChange={this.handleNameChange} />
      </div>
    );
  }
}
  • react적인 접근은 맞지만 항상 맞는 방법이라고 할순 없다
  • 일반적으로, input을 rendering 하는 form component에서 해당 state를 저장함
  • 이런 흐름은 value의 변화를 form component에 넣어준다고 할수 있다.(push value)
  • 이것은 state와 UI(input element)가 항상 동기화 되고있다는 것을 뜻한다.

 

controlled 한 element로 만드는것

  • value를 prop 으로 전달하는 경우 "controlled" 되고있는 element가 된다고 할수있다.

 

결론


두가지 모두 각각의 메리트가 있다

form 이 UI feedback 측면에서 매우 단순하다면 refs를 사용한 uncontrolled input으로 구현되어도 괜찮다.

 

특정 시점(ex-submit)에만 value가 필요한 경우 - uncontrolled

항상 동기화된 value값이 유지되어야 하는경우 - controlled

 

 

 

참고자료

https://goshacmd.com/controlled-vs-uncontrolled-inputs-react/

 

Controlled and uncontrolled form inputs in React don't have to be complicated - Gosha Arinich

There are many articles saying you should use setState, and the docs claim refs are bad. So contradictory. How are you supposed to make forms?

goshacmd.com