React 컴포넌트 외부에서 데이터를 처리하고 받아오는 과정
let foo = 'hello';
function bar() {
foo = 'world';
}
bar();
console.log(foo); //'world' 출력
let c = 12;
function sum(a, b){
return a + b + c
}
let c = 12;
function sum(a, b){
c = a * b;
return a + b;
}
const obj = {value: 12};
function sum(obj, num){
obj.value += num;
}
const obj = {value: 12};
function sum(obj, num){
return {value: obj.value + num};
}
let word = 'hello';
function upper(str) {
return str.toUpperCase(); // toUpperCase 메소드는 원본을 수정하지 않음 (Immutable)
}
console.log(upper(word)); //'HELLO'
console.log(word); //'hello'
function SingleTweet({ writer, body, createdAt }) {
return (
<div>
<div>{writer}</div>
<div>{createdAt}</div>
<div>{body}</div>
</div>
)
useEffect()
: Hook API 중에 하나로, 컴포넌트 내에서 Side effect를 실행함useEffect(함수)
실행시 함수 실행 조건useEffect(() => {
console.log(몇 번 호출될까요?)
})
useEffect(함수, [종속성1, 종속성2, ...])
useEffect(() => {
console.log(몇 번 호출될까요?)
},[])
useEffect(() => {
console.log(몇 번 호출될까요?)
},[dep])
컴포넌트 내에서 필터링
컴포넌트 외부에서 필터링
장점 비교
구분 | 장점 |
---|---|
컴포넌트 내부 처리 | HTTP 요청의 빈도를 줄임 |
컴포넌트 외부 처리 | 클라이언트가 필터링 구현을 생각하지 않아도 됨 |
useEffect(() => {
fetch(`http://서버주소/proverbs?q=${filter}`)
.then(resp => resp.json())
.then(result => {
setProverbs(result);
});
}, [filter]);
const [isLoading, setIsLoading] = useState(true);
// 생략, LoadingIndicator 컴포넌트는 별도로 구현했음을 가정
return {isLoading ? <LoadingIndicator /> : <div>로딩 완료 화면</div>}
fetch
요청 전후로 setIsLoading
설정하기useEffect(() => {
setIsLoading(true); //추가됨
fetch(`http://서버주소/proverbs?q=${filter}`)
.then(resp => resp.json())
.then(result => {
setProverbs(result);
setIsLoading(false); //추가됨
});
}, [filter]);