🔍 Deep Dive - React 렌더링과 상태 기반 재계산 구조
1. 문제 제기
왜 filter 함수를 직접 호출하지 않았는데도
검색 결과가 자동으로 바뀌는가?
2. React의 렌더링 구조
React 함수형 컴포넌트는
state가 변경되면 함수 전체가 다시 실행된다.
const [searchQuery, setSearchQuery] = useState("");
setSearchQuery()가 실행되면
컴포넌트 함수가 처음부터 다시 실행된다.
3. 재실행 과정
- state 변경
- 컴포넌트 재실행
- filter() 재계산
- map() 재실행
- Virtual DOM 비교
- 실제 DOM 업데이트
즉, filter는 "자동 실행"이 아니라
렌더 과정에서 다시 계산되는 것이다.
4. 성능 관점
데이터가 많아질 경우
매 렌더마다 filter()가 실행되므로
useMemo를 활용해 최적화할 수 있다.
const filteredTemplates = useMemo(() => {
return templates.filter((template) => {
if (!searchQuery.trim()) return true;
return template.title
.toLowerCase()
.includes(searchQuery.trim().toLowerCase());
});
}, [templates, searchQuery]);
5. 결론
React는 DOM을 직접 조작하는 구조가 아니라
상태(state)를 기반으로 UI를 재계산하는 구조다.
검색 기능을 통해
React의 렌더링 흐름을 다시 이해하게 되었다.