React 기초(3) - useState

1 minute read

useState의 기본 역할

useState 함수를 통해 값을 손쉽게 변경할 수 있다. 아래와 같이 const [text, setText] = useState('건우')처럼 text는 기본 값을 setText는 변경할 값을 바꾸는 역할을 한다.

import React, { useState } from 'react';

function App() {

  const [text, setText] = useState('건우')

  const updateText = () => {
    setText('상희')
    console.log(text);
  }

  return (
    <div className="App">
      <span>{text}</span>
      <button onClick={updateText}>Update</button>
    </div>
  );
}

export default App;

폼에서 useState 사용하기

폼에서 useState를 유용하게 사용할 수 있는데 크게 2가지를 기본으로 알아두어야 한다.

먼저 input에서 useState를 사용하려면 onChange 이벤트 핸들러를 통해 값을 변경할 수 있게 해야한다. 왜냐하면 value에서 기본 값을 ‘‘으로 설정했기 때문에 onChange를 통해 set~를 변경하지 않으면 값이 바뀌지 않기 때문이다.

다음은 폼을 제출할 때인데, 폼은 제출하면 페이지가 리프레시되기 때문에 값을 확인하려면 onSubmit 이벤트 핸들러를 통해 e.preventDefault()를 지정해 태그가 지닌 고유의 동작을 멈추게 해준다.

화면에 나타나고 변하는 값은 useState를 사용한다고 생각하면 될 거 같다.

import React, { useState } from 'react';

function App() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const onSubmit = (e) => {
    e.preventDefault();
    console.log(username, password)
  }

  return (
    <div className="App">
      <form onSubmit={onSubmit}>
        <input 
          placeholder="Username" 
          value={username} 
          onChange={(e) => setUsername(e.target.value)} /><br />
        <input 
          placeholder="Password" 
          value={password} 
          onChange={(e) => setPassword(e.target.value)}/><br />
        <button type="submit">Login</button>
      </form>
    </div>
  );
}

export default App;

Leave a comment