✅ 입력받은 값(코멘트)을 localstorage에 저장했는데 바로 보여지지 않는 오류가 발생
useState 상태값 바로 변경안될 때
즉시 변경되지 않는 이유?
useState를 이용한 상태 업데이트는 비동기적이기 때문에 변경 사항이 즉시 반영되지 않는다!
useState의 업데이터는 이전 값을 기억하고 있다가 비동기 요청에서 사용 가능한 값으로 바꾼다.
함수형 컴포넌트는 상태 변경이 일어나면 함수를 다시 호출해 렌더링을 해야한다.
즉, useState를 통해 업데이트할 때는 리렌더링이 필요하다.
(useState, useRef)
useRef
저장공간(변수 관리), DOM 요소에 접근하기 위해 사용되는 React Hook이다.
자바스크립트에서 document.querySelector()와 같은 함수를 대신 사용한다고 생각하면 된다.
사용법
import { useState, useRef } from 'react'
import './App.css';
function App() {
const [render, setRender] = useState(false);
const countRef = useRef(0);
let countVar = 0;
console.log('***** 렌더링 후 Ref:', countRef.current);
console.log('***** 렌더링 후 Var:', countVar);
const increaseRef = () => {
countRef.current = countRef.current + 1;
console.log('Ref Up! --->', countRef.current);
}
const increaseVar = () => {
countVar = countVar + 1;
console.log('Var Up! --->', countVar);
}
const doRender = () => {
setRender(!render);
}
return (
<div className="App">
<header className="App-header">
<p>Ref: {countRef.current}</p>
<p>Var: {countVar}</p>
<div>
<button onClick={increaseRef}>Ref Up!</button>
<button onClick={increaseVar}>Var Up!</button>
<button onClick={doRender}>Render!</button>
</div>
</header>
</div>
);
}
export default App;
// 코드 출처: https://itprogramming119.tistory.com/entry/React-useRef-사용법-및-예제 [코딩병원:티스토리]
//useRef 변수를 선언한 후 DOM에 ref로 연결해준다.
const Focus=()=>{
const inputRef=useRef(null);
return(
<input ref={inputRef} ... >
...
❗ useRef는 리렌더링 하지 않는다. 컴포넌트의 속성만 조회&수정한다.
📑 공식문서 (Ref와 DOM)
https://ko.reactjs.org/docs/refs-and-the-dom.html#when-to-use-refs
📌 참고자료