728x90
useEffect : 우리의 코드가 딱 한번만 실행될수 있는 것을 보장해줌
첫번째 인자 : 우리가 실행시키고 싶은 함수
두번째 인자 : dependencies, 이것들이 변화할때 실행시킨다
App.js
import {useEffect, useState} from "react";
function App() {
const [counter, setCounter] = useState(0);
const [keyword, setKeyword] = useState("");
const onClick = () => setCounter((current) => current+1);
const onChange = (event) => {setKeyword(event.target.value)};
useEffect(() => {
console.log("I run only once"); //이건 정말 단한번만 실행됨
}, []);
useEffect(() => {
console.log("I run when 'keyword' changes.");
}, [keyword]); //keyword가 변화할때 코드를 실행하게끔.
useEffect(() => {
console.log("I run when 'counter' changes.");
}, [counter]);
useEffect(() => {
console.log("I run when keyword or counter change");
}, [keyword, counter]);
return (
<div>
<input
value={keyword}
onChange={onChange}
type="text"
placeholder="Search here..."
/>
<h1>{counter}</h1>
<button onClick={onClick}>click me</button>
</div>
);
}
export default App;
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);반응형
'React' 카테고리의 다른 글
| [React] todo (0) | 2022.11.10 |
|---|---|
| [React] useEffect2 cleanup (0) | 2022.11.10 |
| [React] create_react_app기초 (0) | 2022.11.10 |
| [React] create react 설치 후 (0) | 2022.11.09 |
| [React] props (0) | 2022.11.09 |
댓글