250x250
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 파이썬 딕셔너리
- 리액트 공식문서
- JavaScript
- 내일배움캠프 프로젝트
- 한글 공부 사이트
- 리액트
- useEffect
- 코딩테스트
- 내배캠 프로젝트
- typeScript
- Next 팀 프로젝트
- 타입스크립트 props
- 내일배움캠프 최종 프로젝트
- 파이썬 for
- 리액트 훅
- REACT
- 파이썬 for in
- 파이썬 replace
- 내일배움캠프
- 프로그래머스
- tanstack query
- React Hooks
- 파이썬 enumerate
- 자바스크립트
- 파이썬 slice
- useState
- 파이썬 반복문
- 타입스크립트
- 리액트 프로젝트
- 타입스크립트 리액트
Archives
- Today
- Total
sohyeon kim
[React] Custom Hooks : 훅 만들기 본문
728x90
💡 Custom Hooks 을 사용해 보자.
기존 input 값을 받아오던 방식
import { useState } from "react";
function App() {
const [name, setName] = useState("");
const [password, setPassword] = useState("");
const onChangeName = (e) => { // 패스워드 관리 함수와 똑같이 생겼다
setName(e.targe.value);
};
const onChangePassword = (e) => { // 네임 관리 함수와 똑같이 생겼다
setPassword(e.targe.value);
};
return (
<div>
<h2>Custom Hooks</h2>
<input type="text" value={name} onChange={onChangeName} />
<input type="password" value={password} onChange={onChangePassword} />
</div>
);
}
export default App;
반복되는 함수들을 정리할 우리만의 Hook 을 만들어보자!
hooks 폴더 내 useInput.js 생성
import { useState } from "react";
export const useInput = () => {
const [value, setValue] = useState(""); // App.jsx 에서 쓰던 useState 를 여기서 쓴다.
const handler = (e) => {
setValue(e.target.value);
};
return [value, handler];
};
App.jsx
import "./App.css";
import { useInput } from "./hooks/useInput";
function App() {
const [name, onChangeName] = useInput();
const [password, onChangePassword] = useInput();
return (
<div>
<h2>Custom Hooks</h2>
<input type="text" value={name} onChange={onChangeName} />
<input type="password" value={password} onChange={onChangePassword} />
</div>
);
}
export default App;
반복되는 함수를 아예 없앨 수 있다!
~ 활용 ~
** value = id, handler = setId, resetInput = setId 인 것 ~
useInput.jsx
import { useState } from "react";
export const useInput = (initialState = "") => {
const [value, setValue] = useState(initialState);
const handler = (e) => {
setValue(e.target.value);
};
const resetInput = () => {
setValue(initialState);
};
return [value, handler, resetInput];
};
Login.jsx
const [pwd, setPwd, resetInput] = useInput();
// ...
// 회원가입 성공 시 실행
resetInput(); // input 값을 초기화한다.
728x90
반응형
'React' 카테고리의 다른 글
[React] React Query : 미들웨어 대신 리액트 쿼리 (0) | 2024.02.20 |
---|---|
[React] Error : Cannot read properties of null (reading 'useMemo') (0) | 2024.02.20 |
[React] Redux Thunk App (0) | 2024.02.20 |
[React] Redux Thunk : 미들웨어 (0) | 2024.02.19 |
[React] axios & interseptor : api 생성, URL 생략 & 요청, 응답 사이에 관여 (0) | 2024.02.19 |