다시 Next js를 하면서
Next js에서 사용하는 Hooks 들을 정리해보려 한다.
UseRef
- Dom 요소에 접근
예를 들어서, input 에 inputRef 을 통해 접근을 하고,
<input> 에 속성으로 전달을 한다.
그 이후에,
useEffect 내부에
inputRef.current.focus();
를 적용 해줌으로써, DOM요소에 직접 컨택할 때 쓰인다.
import React, { useRef, useEffect } from 'react';
function FocusInput() {
const inputRef = useRef(null);
useEffect(() => {
// 컴포넌트가 마운트될 때 input 요소에 포커스
inputRef.current.focus();
}, []);
return <input ref={inputRef} type="text" />;
}
export default FocusInput;
2. 리렌더링 되더라도 변하지 않는 값 저장
여기서 count 는 useRef를 통해 유지 되고,
버튼을 누를 때 마다 count.current의 값은 +1 씩 상승하지만,
리렌더링은 되지 않습니다.
function Timer() {
const count = useRef(0);
const increment = () => {
count.current += 1;
console.log(count.current);
};
return <button onClick={increment}>Increment</button>;
}
3. 렌더링 되기 전 이전 값 기억
아래의 코드에서
value의 이전 값을 prevValue에 저장을 하고 ,
value가 바뀜에 따라 렌더링을 다시 하지만,
value 와 prevValue의 값은 다르다.
function PreviousValue({ value }) {
const prevValue = useRef(value);
useEffect(() => {
prevValue.current = value;
}, [value]);
return (
<div>
<p>Current Value: {value}</p>
<p>Previous Value: {prevValue.current}</p>
</div>
);
}
PS.
useRef 는 .current 라는 속성을 가진 객체를 반환하며,
.current를 통해 값을 읽거나, 쓸 수 있다.
'개발 - Next.js' 카테고리의 다른 글
Next js (넥스트 js) - SessionStorage , localStorage (자체 데이터) (2) | 2024.10.17 |
---|---|
Next js (넥스트 js)- Hook 5편 - useContext (0) | 2024.10.17 |
Next js (넥스트 js)- Hook 4편 - useCallback (0) | 2024.10.17 |
Next js (넥스트 js)- Hook 3편 - useDropZone (0) | 2024.10.17 |
Next js (넥스트 js)- Hook 2편 - useEffect (1) | 2024.10.17 |