반응형
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
- useState #Hooks
- 백준 #적록색약
- 빡킹독
- React #Hook rules #Hook 규칙
- react
- 코드스테이츠 #알고리즘 #그리디
- RateLimit
- rate limit
- DP #c++
- donwstream #upstream #origin
- html entities
- npm #not being able to find a file #npm install Error
- 플로이드 #c++
- 노마드 코더 #타입스크립트 #typescript #class
- React #effect hook #useEffect
- raect typescript #react #typescript #styled-component
- react fragment
- axios
- 이친수
- React #리액트 이벤트 주기 #리액트 이벤트
- #useRef #언제 쓰는데?
- 다익스트라 #파티 #백준
- 얕은 복사 #깊은 복사 #shallow copy #deep copy
- JWT #토큰 #refreshToken #accessToken #Token #token #localStorage #sessionStorage
- react #useCallback #react Hook
- React-Query
- 버블링 #갭쳐링 #이벤트 #JS
- React #controlled component #비제어 컴포넌트 #제어 컴포넌트
- 백준 #직각삼각형
- interceptors
Archives
- Today
- Total
꿈꾸는 개발자
React useState/Input state 관리-Hooks 본문
리액트 16.8 이전에는 함수형 컴포넌트에서 상태 관리가 불가능했다 => react 16.8에서 Hooks이란 기능이 도입되면서 함수형 컴포넌트에서도 상태 관리가 가능해졌다! (useState도 Hooks 중 하나!)
이벤트 설정:
import React from 'react';
function Counter() {
const onIncrease = () => {
console.log('+1')
}
const onDecrease = () => {
console.log('-1');
}
return (
<div>
<h1>0</h1>
<button onClick={onIncrease}>+1</button>
<button onClick={onDecrease}>-1</button>
</div>
);
}
export default Counter;
- react에선 이벤트를 설정할 때 on이벤트이름={실행하고싶은함수} 형태로 사용해야 한다! => 단 함수호출이 아닌, 함수명만 입력을 해야 한다!
동적인 값 끼얹기, useState
import React, { useState } from 'react';
function Counter() {
const [number, setNumber] = useState(0);
const onIncrease = () => {
setNumber(number + 1);
}
const onDecrease = () => {
setNumber(number - 1);
}
return (
<div>
<h1>{number}</h1>
<button onClick={onIncrease}>+1</button>
<button onClick={onDecrease}>-1</button>
</div>
);
}
export default Counter;
const [number, setNumber] = useState(0);
- 배열을 반환한다 => 첫 번째 원소는 현재 상태이고 두 번째 원소는 setter함수를 반환한다!
function ExampleWithManyStates() {
// 여러 개의 state를 선언할 수 있습니다!
const [age, setAge] = useState(42);
const [fruit, setFruit] = useState('banana');
const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
- 여러개의 state를 사용하면, 재각각 변수를 선언할 수 있어서 유용하다!
useState callback 함수 사용:
// import logo from "./logo.svg";
import "./App.css";
import { useState } from "react";
function App() {
const [number, setNumber] = useState(0);
const increase = () => {
setNumber((preNumber) => preNumber + 1);
};
const decrease = () => {
//밑 setNumber에 콜백함수를 넣으면, 이전의 값을 가져온다!
setNumber((preNumber) => preNumber - 1);
};
return (
<div>
<h1>{number}</h1>
<button onClick={increase}>+</button>
<button onClick={decrease}>-</button>
</div>
);
}
export default App;
- 위 setNumber에 콜백함수를 매개변수로 넣은 준 것을 확인할 수 있다
- 콜백함수를 매개변수로 넣어줄 경우, 콜백함수의 인자로 이전 상태값을 가지게 된다! (number의)
- return 값에는 새로운 state 지정이 가능하다!
useState을 통한 Input 상태 관리
import React from "react";
import { useState } from "react";
function InputSample() {
const [state, setState] = useState(0);
const inputChange = (event) => {
setState(event.target.value);
};
const reset = () => {
setState("");
};
return (
<div>
<input onChange={inputChange} />
<button onClick={reset}>초기화</button>
<div>값:{state}</div>
</div>
);
}
export default InputSample;
// import logo from "./logo.svg";
import "./App.css";
import InputSample from "./InputSample";
function App() {
return <InputSample />;
}
export default App;
출처:
https://react.vlpt.us/basic/07-useState.html
https://developer-talk.tistory.com/229
https://ko.reactjs.org/docs/hooks-state.html