prop Drilling을 막기 위해 최상위 검색 상태값 useState대신 useRef 사용 #1
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
문제 정의
상위 컴포넌트의 상태값을 바로 넘겨버리기 때문에 search, setSearch 값이 변할 때마다 재렌더링이 일어남.
이 현상은 지역 변수의 경우에도 똑같지만, SearchField 컴포넌트를 포함하고 있는 Header 컴포넌트 자체가 재렌더링되기 때문에 autofocus등 입력 기능이 잘 되지 않는 문제가 발생함.
해결 방법
useRef의 반환값인 ref 객체는 값이 변해도 재렌더링이 되지 않으므로 적절하다고 생각되었음. (object는 reference type이므로)
간단하게 useState 대신 useRef를 통해 현재값을 갱신시킴.
추후 값 사용이 필요할 경우 searchRef.current를 사용하면 될 듯함.