useMemo, useCallback & Data Fetching, HTTP Requests
How Does React Update the DOM?
and how are component functions executed?
mian.jsx 루트 객체 생성 후 앱 컴포넌트를 화면에 렌더링 (리액트를 통해 실행)
모든 컴포넌트 함수는 렌더링 되는 것들만 반환하며,
jsx는 결과적으로 js코드로 변환되고, 화면에 렌더될 수 있는 실제 요소로 변환된다.
코드 흐름에 따라 컴포넌트 트리에 순차적으로 추가되며 실행됨.
memo() : 컴포넌트 함수를 감싸는데 사용
이전값과 현재 값(내부상태)을 비교하여 함수의 재실행을 억제.
Don't overuse memo() !
Use it as high up in the component tree as possible
-> blokcing a component execution there will also block all child component executions
Checking props with memo() costs performance!
-> don't wrap it around all your components - it will just add a lot of unnecessary checks
Don't use it on components where props will change frequently
-> memo() would just perform a meaningless check in such cases(which costs performance)
useMemo() : 일반 함수를 감싸는데 사용. 복잡한 계산이 있는 경우에만 사용. 값을 기억
useCallback() : 값이 아닌 함수 자체를 기억. 함수가 컴포넌트 내부에서 정의될 때 주로 사용.
HTML 파일은 리액트가 DOM으로 삽입.
개발자 도구에서 html 요소 중 업데이트 되는 부분에 깜빡이는 걸 볼 수 있는데,
변경되는 일부분만 업데이트 함을 확인해 볼 수 있다.
React checks for necessary DOM updates via a "Virtual DOM"
It creates & compoares virtual DOM snapshots to find out which parts of the rendered UI need to be updated.
가상 돔을 사용함으로써 메모리안에만 존재하고, 실제 DOM보다 속도도 더 빠르다.
virtual dom snapshot 과 old snapshot을 비교, 변동사항만을 적용.
key ? 형제 컴포넌트가 존재할 대. 상태를 구체적인 컴포넌트 인스턴스에 맵핑할 때 사용.
같은 함수 내에서 여러 state update가 있을때 state batching을 수행 -> 한번의 컴포넌트 실행을 유도
https://academind.com/tutorials/this-keyword-function-references
'this' Keyword & Function References
The 'this' keyword can lead to a lot of confusion in JS. So can function calls without parenthesis. What's the idea behind this.someFunction.bind(this)?
academind.com
Million.js package 리액트 앱의 성능을 최적화하는데 사용
Data Fetching & HTTP Requests
How To connect a backend/database
fetching / sending data
You Don't at least not directly. 리액트와 직접적으로 연결하는 것은 보안상 문제가 있음
Always keep in mind Your React code runs in the browsers of your users
They can view that code (via the browser developer tools) if they want to!
There also are technical restrictions & constraints
Not all operations can be performed in the browser
E.g, you can't access a (centrally managed) file system
Communicate with a backend Server instead.
Front < = HTTP => Backend
https://developer.mozilla.org/en-US/docs/Web/HTTP
https://www.youtube.com/watch?v=0oXYLzuucwE
useEffect( () => {
async function fetchPlaces() {
setIsFetching(true);
try{
const response = await fetch ('~');
const resData = await response.json();
if(!response.ok){
throw new Error('Fail');
}
setAvailablePlaces(resData.places);
} catch(error){
setError(error);
}
setIsFetching(false);
}
fetchPlaces();
}, []);
useEffect ()를 사용하여 무한 루프를 해결.
함수 내부에서 async와 await을 사용, fetch함수를 통해 통신.
개발자 도구 -> 네트워크 -> throttling 활성화, Slow 3G 후 새로고침 시 로딩 속도가 느려지게 됨.
(느린 인터넷 환경에서의 사용자 경험을 테스트, 로딩 텍스트를 보여주자!)
이를 위해서는 loading state를 관리해주어야 함.
네트워크 충돌이 일어나거나, 애초에 요청을 실패할 수 있기 때문에 Frontend에서의 실패에 대한 반응이 필요하다.
비동기를 사용한 모든 함수는 promise를 반환.
Post를 통해 전송하고자 할 때는 첨부될 수 있는 형태의 데이터를 담아주어야 하는데,
기존 JAVA 배열은 불가하므로, JSON.stringify()를 사용하자.
"백엔드는 특정 종류의 요청과 원하는 데이터만을 받는다. "