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
- Spring Framework
- select
- 개발기록
- 오버라이딩
- 외부조인
- DAO
- react
- ChainMap
- JIT
- 백준
- 자바
- java
- 청크
- 싱글톤
- 스프링
- overriding
- 리스트 자르기
- GCP Storage
- defaultdict
- spring
- null
- 데이터베이스
- DAO의 분리
- 121
- 파이썬
- PYTHON
- Oracle
- 싱글톤 레지스트리
- orderedDict
- 쓰는이유
Archives
- Today
- Total
PengTory
useEffect, useState 본문
useState를 사용하면 내가 state를 변경할 때 마다 모든 코드들이 그대로 다시 실행된다.
아래 코드같은 경우에는 버튼 클릭마다 "call on API"라는 콘솔이 계속해서 찍힌다.
import Button from "./Button";
import styles from "./App.module.css";
import {useState} from "react";
function App() {
const [counter, setValue] = useState(0);
const onClick = () => setValue((prev) => prev + 1);
console.log("call on API");
return (
<div>
<h1 className={styles.title}>{counter}</h1>
<button onClick = {onClick}>click me</button>
</div>
);
}
export default App;
만약 내가 API를 호출하는 것 처럼 반복하지 않고 딱 한번만 실행되게 하고 싶다면 useState 대신 무엇을 써야할까?
답은 useEffect다.
useEffect에는 컴퍼넌트가 처음 렌더링할 때 실행되고 다시는 실행되지 않을 함수를 넣어준다. 이를 통해 코드가 딱 한번만 실행될 수 있도록 보호해준다.
import Button from "./Button";
import styles from "./App.module.css";
import {useState, useEffect} from "react";
function App() {
const [counter, setValue] = useState(0);
const onClick = () => setValue((prev) => prev + 1);
console.log("I run all the time");
useEffect(() => {
console.log("Call The API...");
}, []);
return (
<div>
<h1 className={styles.title}>{counter}</h1>
<button onClick = {onClick}>click me</button>
</div>
);
}
export default App;
위 로그를 보면 useEffect 안에 있는 로그 'Call The API'는 처음 한번만 찍히고, counter state가 변할 때는 찍히지 않는 것을 확인할 수 있다.
useEffect는 두 개의 argument를 가지는 함수이다. 첫번 째 argument는 딱 한번만 실행하고 싶은 코드를 넣는다.
두번째 argument는 특정 부분이 변화할 때 코드를 실행할 것이라고 react.js에 알려주기 위해 사용한다.
import Button from "./Button";
import styles from "./App.module.css";
import {useState, useEffect} from "react";
function App() {
const [counter, setValue] = useState(0);
const [keyword, setKeyword] = useState("")
const onClick = () => setValue((prev) => prev + 1);
const onChange =(event) => setKeyword(event.target.value);
console.log("I run all the time");
useEffect(() => {
console.log("Call The API...");
}, []);
useEffect(() => {
if(keyword !== "" && keyword.length > 5){
console.log("SEARCH FOR", keyword);
}
}, [keyword]);
return (
<div>
<input value ={keyword}
onChange={onChange}
type ="Text"
placeholder="Search here..."/>
<h1 className={styles.title}>{counter}</h1>
<button onClick = {onClick}>click me</button>
</div>
);
}
export default App;
다음과 같이 useEffect{( ) => { },[ ] } 에서 [ ] 자리에 변화에 집중하고 싶은 특정 state를 적어주면 그 state가 업데이트 될 때 마다 useEffect 안에 있는 로그가 찍히는 것을 볼 수 있다.
if 문 안의 조건에 따라 5글자부터 SEARCH FOR 로그가 찍히며 count 버튼을 눌럿을 때는 SEARCH FOR과 관련된 로그가 찍히지 않는 것을 확인할 수있다.
'React' 카테고리의 다른 글
React로 간단 ToDoList 만들기 (0) | 2022.07.19 |
---|---|
<select> 시간 <-> 분 구현, Km <-> Mile (0) | 2022.07.18 |