여러 컴포넌트에서 비슷한 기능을 공유할 경우 사용자 정의 custom hook을 작성하여 로직을 재사용 할 수 있음
problem
const { useState } = React;
function App() {
const [username, setUsername] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleUsername = (e) => setUsername(e.target.value);
const handleEmail = (e) => setEmail(e.target.value);
const handlePassword = (e) => setPassword(e.target.value);
return (
<div>
<label>이름 : </label>
<input type="text" id="username" value={ username } onChange={ handleUsername } />
<br/>
<label>비밀번호 : </label>
<input type="password" id="password" value={ password } onChange={ handlePassword } />
<br/>
<label>이메일 : </label>
<input type="email" id="email" value={ email } onChange={ handleEmail } />
<br/>
<h4>usename : { username }</h4>
<h4>password : { password }</h4>
<h4>email : { email }</h4>
</div>
);
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
const { useState } = React;
function useInput(){
const [value, setValue] = useState('');
const onChange = (e) => setValue(e.target.value);
return {value, onChange};
}
function App() {
const username = useInput();
const password = useInput();
const email = useInput();
return (
<div>
<label>이름 : </label>
<input type="text" id="username" value={username.value} onChange = {username.onChange} />
<br/>
<label>비밀번호 : </label>
<input type="password" id="password" {...password} />
<br/>
<label>이메일 : </label>
<input type="email" id="email" {...email} />
<br/>
<h4>usename : { username.value }</h4>
<h4>password : { password.value }</h4>
<h4>email : { email.value }</h4>
</div>
);
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />);