import { useState } from "react";
function App() {
const [counter, setValue] = useState(0);
const onClick = () => setValue((prev) => prev + 1);
return (
<div>
<h1>{counter}</h1>
<button onClick={onClick}>click me</button>
</div>
);
}
export default App;
import { useState, useEffect } from "react";
function App() {
const [counter, setValue] = useState(0);
const onClick = () => setValue((prev) => prev + 1);
console.log("render");
const iRunOnlyOnce = () => {
console.log("iRunOnlyOnce");
};
useEffect(iRunOnlyOnce, []);
return (
<div>
<h1>{counter}</h1>
<button onClick={onClick}>click me</button>
</div>
);
}
export default App;
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");
const iRunOnlyOnce = () => {
console.log("iRunOnlyOnce");
};
useEffect(iRunOnlyOnce, []);
useEffect(() => {
if (keyword !== "" && keyword.length > 5) {
console.log("search for " + keyword);
}
}, [keyword]);
return (
<div>
<input
value={keyword}
onChange={onChange}
type="text"
placeholder="Search"
></input>
<h1>{counter}</h1>
<button onClick={onClick}>click me</button>
</div>
);
}
export default App;
-컴포넌트가 destroyed 될때, maybe 컴포넌트가 사라질때 analysis 결과를 보내거나 분석 API 를 보내겟지 evnent listner 를 하거나 사용 된다.
function Hello() {
useEffect(() => {
console.log("created :)");
//처음 한번만 실행 하지만 아래 ui 처럼 클릭 할때마다 실행 create, destroy 될때마다
return () => console.log("destroyed :("); //cleanup function
}, []);
return <h1>Hello</h1>;
}
function Hello() {
function byeFn() {
console.log("bye :<");
}
function hiFn() {
console.log("hi :)");
return byeFn; //리턴 값이 있기 때문에 한번만 실행..?
}
useEffect(hiFn, []);
return <h1>Hello</h1>;
}
function App() {
const [showing, setShowing] = useState(false);
const onClick = () => {
setShowing((prev) => !prev);
};
return (
<div>
{showing ? <Hello /> : null}
<button onClick={onClick}>{showing ? "hide" : "show"}</button>
</div>
);
}
export default App;