지난시간에 공부한 내용의 연장선상이지만,
리액트는 특정 원소가 변했을 때만 반응할 수 있게 우리를 도와준다.
다음 코드를 살펴보자
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 helps us to call a code only one time
useEffect(() => {
console.log("I run only once.");
}, []);
// This code runs every time the keyword changes
useEffect(() => {
// if the keyword is longer than 5 -> working
if (keyword.length > 5) {
console.log(`I run when ${keyword} changes`);
}
}, [keyword]);
// This code runs every time the counter changes
useEffect(() => {
console.log(`I run when ${counter} chagnes`);
}, [counter])
// This code runs every thime either the counter or keyword changes
useEffect(() => {
console.log('I run when counter or keyword changes');
},[counter, keyword])
return (
<div>
<input
value={keyword}
onChange={onChange}
type="text"
placeholder="Search here...">
</input>
<h1>{counter}</h1>
<button onClick={onClick}>click me</button>
</div>
);
}
export default App;
useEffect(() => {변했을때 취할 액션}, [변했을때 반응했으면 하는 원소])
를 사용하여, 변했을 때 반응했으면 하는 원소와 변했을 때 취할 액션을 정할 수 있다.
'FrontEnd > React' 카테고리의 다른 글
| [ReactJS] map() 매서드의 활용 (0) | 2023.01.12 |
|---|---|
| [ReactJS] useEffect() 의 활용 (0) | 2023.01.11 |
| [ReactJS] useEffect (0) | 2023.01.10 |
| [ReactJS] Prop Types (0) | 2023.01.09 |
| [ReactJS] memo (0) | 2023.01.09 |