1. useState
(1) useState는 react의 가장 기본적인 hook으로 함수형 컴포넌트 내에서 상태 값을 관리하고, 상태가 변화하면 리렌더링을 하여
반영시킨다.변적인 상태를 갖게 한다.
(2) const [state, setState] = useState(초기값);
2. useRef
(1) useRef는 DOM 요소를 어딘가에 저장하고 접근해서 DOM 요소를 사용할 수 있도록 도와주는 react hook이다.
(2) const ref = useRef( );
3. useState vs useRef : 리렌더링 여부
(1) useState는 state의 변화가 일어나면 다시 렌더링되고 내부 변수들이 초기화됨.
(2) useRef에 저장된 값이 변해도 내부 변수들이 초기화되지 않고 리렌더링이 일어나지 않음.
4. useState vs useRef : input 내부 값의 관리를 확인하는 코드
둘의 차이를 비교하기위해 새로운 react project를 생성한 뒤, 각각 useState, useRef로 관리되는 input 창을 만들었다.
import React, { useState, useRef } from "react";
function App() {
const [value, setValue] = useState("");
const inputRef = useRef(null);
return (
<div>
<div>
useState :
<input
value={value}
onChange={(event) => {
setValue(event.target.value);
console.log("useState render");
}}
></input>
</div>
<div>
useRef : <input ref={inputRef}>{console.log("useRef render")}</input>
</div>
</div>
);
}
export default App;
두 개의 input 창에 입력하면서 개별적으로 console.log를 찍어봤을 때,
1) useState의 input
값을 입력할 때마다 rendering 횟수가 증가했다.
2) useRef의 input
처음 새로고침을 했을 때만 rendering되고 input 창에 값을 입력해줘도 rendering 횟수가 그대로 였다.
3) 차이점은 3번의 내용과 마찬가지로 re-rendering의 여부였다.
5. input 내부의 값을 효율적으로 관리하는 방법
1) React의 입장
React에서 가장 cost가 많이 드는 작업이 화면에 element를 그려주는 painting 이다.
그만큼 불필요한 re-rendering의 횟수를 줄이는 것이 해당 app의 효율성을 높이는 방법이다.
이런 관점에서 본다면 input 내부의 값을 useRef로 관리하는 것이 더 효율적인 방법일 것이다.
2) 사용자의 입장
하지만, 사용자의 입장에서 input 창에 값을 입력하면서 그 변화를 바로바로 확인하는 것이 더 좋은 UI가 아닐까?
예를 들어, 나는 검색 엔진에서 키워드를 검색하거나 넥플릭스 등에서 원하는 컨텐츠를 검색하는 경우가 굉장히 많다.
이때 내가 입력하는 검색어에 따라 실시간으로 변화가 반영되어 연관성이 높은 것을 제시해주는 것이 당연하다고 생각하고,
완벽히 일치하는 검색어를 입력해야만 결과를 반영해준다면 불편해서 이용하고 싶지 않을 것 같다.
3) 그래서 양쪽 입장을 고려했을 때, useState로 input 내부의 값을 관리하는 것이 더 좋다고 생각한다.
6. Controlled vs Uncontrolled
Controlled Components
In HTML, form elements such as <input>, <textarea>, and <select> typically maintain their own state and update it based on user input. In React, mutable state is typically kept in the state property of components, and only updated with setState().
We can combine the two by making the React state be the “single source of truth”. Then the React component that renders a form also controls what happens in that form on subsequent user input. An input form element whose value is controlled by React in this way is called a “controlled component”.
Uncontrolled Components
In most cases, we recommend using controlled components to implement forms. In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.
To write an uncontrolled component, instead of writing an event handler for every state update, you can use a ref to get form values from the DOM.
1) Controlled Components
input, textarea, select와 같은 form elements는 user의 input에 의해 업데이트가 되고 mutable state, 즉 상호작용을 하는 상태는 react의 controlled component인 setState( )로 관리한다.
즉, input 내부의 값은 useState로 관리하는 것을 권장한다.
2) Uncontrolled Components
form data가 DOM에 의해 handling된다면, useRef를 이용해 DOM으로부터 form의 값을 가져와 사용할 수 있다.
예를 들어, 렌더링 되자마자 특정 input이 focus되는 경우가 그렇다.
'개념 공부' 카테고리의 다른 글
20240206 TIL#32 (0) | 2024.02.19 |
---|