-
13. useRef가 필요한 상황, 14.cookie의 MaxAge, expires옵션항해99 2023. 4. 4. 14:13728x90
Q. useRef가 필요한 상황을 예시를 들어 설명해주세요
1. 폼요소에 자동으로 초점을 맞출 때.
useRef를 이용해 해당 요소를 선택하고 focus()메서드를 호출하여 초점을 설정할 수 있다.2. 이전 상태 저장하기
useState 를 이용할 때 이전샅애를 유지하고 싶은 경우, useRef를 사용하여 이전 값을 저장하고 변경을 추적할 수 있습니다. 이것ㅅ은 상태가 변경되어도 컴포넌트가 다시 렌더링 될 때마다 동일한 값을 유지할 수 있습니다.
3. 애니메이션 컨트롤
useRef를 이용하여 애니메이션을 컨트롤 할 수 있습니다. 애니메이션을 시작, 일시중지 또는 싸디 시작할 때 사용됩니다.
4. DOM요소 조작
useRef를 사용하여 DOM요소에 직접 접근하고 해당 요소의 속성을 변경할 수 있습니다. 이것은 특정 요소의 위치를 변경하거나 크기를 조정하는 경우 유용합니다.
5. 외부 라이브러리와 상호작용하기
외부 라이브러리를 사용할 때, useRef를 사용하여 라이브러리와 상호작용을 할 수 있습니다. 예를 들어, 외부 라이브러리가 생성한 DOM요소에 대한 참조를 가져와서 해당 요소를 변경하거나 조작할 수 있습니다.폼요소에 자동으로 초점을 맞출 때 example
import React, { useState, useRef } from 'react'; function InputTest() { const [text, setText] = useState(''); const nameInput = useRef(); const onChange = e => { setText(e.target.value) }; const onReset = () => { setText(''); nameInput.current.focus(); }; return ( <div> <input name="name" onChange={onChange} value={text} ref={nameInput} /> <button onClick={onReset}>초기화</button> <div> <b>내용: </b> {text} </div> </div> ); } export default InputTest;
선택하고싶은 DOM인 input에 ref값을 설정해준다.
nameInput이 useRef로 ref객체화되어있다. ref={nameInput}으로 지정해줌
nameInput.current.focus()로 선택하고자하는 DOM(input)을 가리키게 한다.
Q. Cookie의 MaxAge, Expires 옵션이 무엇인지, 설정하지 않으면 어떻게 되는지 설명해주세요.
HTTP쿠키에는 이름, 값, 만료시간등의 속성이 포함되는데, 이중에서 MaxAge와 Expires는 쿠키의 만료시간을 설정하는데 사용되는 속성입니다.
Max Age: 쿠키의 만료시간을 초단위로 지정합니다. 쿠키가 생성된 이후 지정된 시간이 지나면 쿠키가 만료되고, 삭제됩니다. 이 값을 설정하며 브라우저가 쿠키를 저장할 때 쿠키가 삭제될 시점을 브라우저 내부 시간으로부터 설정한 만료시간 이후로 계산합니다.
Expirres: 쿠키의 만료 날짜와 시간을 GMT(세계 표준 시간대)기준으로 지정합니다. 쿠키가 만료될 때, 브라우저는 현재 GMT시간과 쿠키의 만료날짜 및 시간을 비교하여 쿠키를 삭제합니다.
설정하지 않으면 어떻게 되는지
이 두가지 속성 중 적어도 하나는 반드시 설정되어야 합니다. 만약 이 속성들 중 하나도 설정하지 않은 경우, 쿠키는 세션쿠키로 취급되어 브라우저 세션이 종료될 때 자동으로 삭제됩니다. 즉,사용자가 브라우저를 닫거나 세션을 종료할 때 까지 유지됩니다.
728x90'항해99' 카테고리의 다른 글
17. Semantic HTML의 필요성, 18. Redux 주요개념들과 연결관계, 다른 상태관리도구와의 비교 (0) 2023.04.07 15.순수함수. 불변성과 사이드이펙트 16. 리액트의 state와 props (0) 2023.04.05 11. import&require차이점, 12. const선언시 배열과객체의 요소나 속성을 추가할 수 있는 이유 (0) 2023.04.03 9. this의 동작원리, 용법 10.브라우저 저장소간의 차이점 (0) 2023.04.02 면접대비 7. HTTP메세지구조 8. CSS position속성 (0) 2023.03.30