💡 숫자 카운팅하는 페이지를 만들어서, state와 useEffect, cleanUp에 대해서 공부해보자
import {useState} from 'react';
function App() {
// create-react-app을 써서 React.을 써줄 필요가 없음
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;
React.useState()
이런식으로 앞에 React.
을 작성해줬는데 create-react-app
을 써서 생략이 가능하다.counter
은 0부터 시작한다.button
을 클릭하면 +1씩해서 counter을 1개씩 플러스 해준다.import {useState} from 'react';
function App() {
// create-react-app을 써서 React.을 써줄 필요가 없음
const [counter, setValue] = useState(0);
const onClick = () => setValue((prev) => prev + 1);
console.log('call an api');
return (
<div>
<h1>{counter}</h1>
<button onClick={onClick}>click me</button>
</div>
);
}
export default App;
{counter}
만 리렌더링되는게 아니라 console.log('call an api');
-> 이 문장도 계속해서 같이 리렌더링된다.function App() {
const [counter, setValue] = useState(0);
const onClick = () => setValue((prev) => prev + 1);
console.log('i run all the time');
const iRunOnlyOnce = () => {
console.log('I run only once.');
};
useEffect(iRunOnlyOnce, []);
return (
<div>
<h1>{counter}</h1>
<button onClick={onClick}>click me</button>
</div>
);
}
useEffect
Hook은 페이지가 처음 렌더링 되고 난 후 useEffect: 글자를 타이핑 할 때마다 리렌더링 된다!!!
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...');
}, []);
return (
<div>
<input
value={keyword}
onChange={onChange}
type="text"
placeholder="Search here..."
/>
<h1>{counter}</h1>
<button onClick={onClick}>click me</button>
</div>
);
}
input
태그의 value가 바뀔 때마다 리렌더링된다.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(() => {
// keyword가 바뀔 때 리렌더링 하고 싶으면 []안에 keyword를 적으면됨
console.log('Search for', keyword);
}, [keyword]);
return (
<div>
<input
value={keyword}
onChange={onChange}
type="text"
placeholder="Search here..."
/>
<h1>{counter}</h1>
<button onClick={onClick}>click me</button>
</div>
);
}
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 > 6){
console.log('Search for', keyword);
}
}, [keyword]);
return (
<div>
<input
value={keyword}
onChange={onChange}
type="text"
placeholder="Search here..."
/>
<h1>{counter}</h1>
<button onClick={onClick}>click me</button>
</div>
);
}
if(keyword !== "" && keyword.length > 6)
조건을 걸어서 조건이 충족되면 keyword의 state가 변경되었을 때 리렌더링 하게끔 할 수 있다.function App() {
const [counter, setValue] = useState(0);
const [keyword, setKeyword] = useState('');
const onClick = () => setValue((prev) => prev + 1);
const onChange = (event) => setKeyword(event.target.value);
useEffect(() => {
console.log('I run only once.');
}, []);
useEffect(() => {
console.log("I run when 'keyword' changes.");
}, [keyword]);
useEffect(() => {
console.log("I run when 'counter' changes.");
}, [counter]);
useEffect(() => {
console.log("I run when keyword & counter changes.");
}, [keyword, counter]);
return (
<div>
<input
value={keyword}
onChange={onChange}
type="text"
placeholder="Search here..."
/>
<h1>{counter}</h1>
<button onClick={onClick}>click me</button>
</div>
);
}
import { useState, useEffect } from 'react';
function App() {
const [showing, setShowing] = useState(false);
const onClick = () => setShowing((prev) => !prev);
return (
<div>
<button onClick={onClick}>{showing ? "Hide" : "Show"}</button>
</div>
);
}
export default App;
function Hello() {
return <h1>Hello</h1>;
}
function App() {
const [showing, setShowing] = useState(false);
const onClick = () => setShowing((prev) => !prev);
return (
<div>
{ // JS 쓸 때는 중괄호 쓰는 거 기억하기!
showing ? <Hello /> : null
}
<button onClick={onClick}>{showing ? "Hide" : "Show"}</button>
</div>
);
}
function Hello() {
useEffect(() => {
console.log("created :)");
return () => console.log("destroyed :("); // cleanUp Function
}, []);
return <h1>Hello</h1>;
}
function App() {
const [showing, setShowing] = useState(false);
const onClick = () => setShowing((prev) => !prev);
return (
<div>
{ // JS 쓸 때는 중괄호 쓰는 거 기억하기!
showing ? <Hello /> : null
}
<button onClick={onClick}>{showing ? "Hide" : "Show"}</button>
</div>
);
}
function Hello() {
function byeFn() {
console.log("bye :(");
}
function hiFn() {
console.log("created :)");
return byeFn;
}
useEffect(hiFn, []);
return <h1>Hello</h1>;
}
useEffect(function() {
console.log("hi :)");
return function () {
console.log("bye :(");
};
}, []);
useEffect(() => {
console.log("hi :)");
return () => console.log("bye :(");
}, []);