728x90
import React, {useRef, useState} from 'react';
const UseRef = () => {
const [renderer, setRenderer] = useState(0); // 숫자 증가시 화면 랜더링 발생
const countRef = useRef(0); // 숫자 증가해도 화면 랜더링 없음
let countVar = 0; // 화면 랜더링 발생하면 값 초기화 발생
const doRendering = () => {
setRenderer(renderer + 1);
}
const increaseRef = () => {
countRef.current = countRef.current + 1;
console.log('ref:', countRef.current);
}
const increaseVar = () => {
countVar = countVar + 1;
console.log('var:', countVar);
};
return (
<div>
<p>Ref: {countRef.current}</p>
<p>Var: {countVar}</p>
<button onClick={doRendering}>랜더 UP</button>
<button onClick={increaseRef}>Ref UP</button>
<button onClick={increaseVar}>Var UP</button>
</div>
);
};
export default UseRef;
|
import logo from './logo.svg';
import './App.css';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import useWindowWidth from "./hooks/useWindowWidth";
import UseRef from "./components/UseRef";
function App() {
const width = useWindowWidth();
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo"/>
<UseRef />
{width}
</header>
</div>
);
}
export default App;
|
useEffect 와 useState를 잘못 사용하면 무한 랜더링이 발생할 수 있다.
useRef를 useEffect 와 사용하면 문제가 해결될 수 있으니 알아두자.
import React, {useRef, useState} from 'react';
const UseRefInput = () => {
const [inputValue, setInputValue] = useState('');
const useridInput = useRef();
const onRest = () => {
setInputValue('');
useridInput.current.focus();
};
return (
<div>
<input type="text" name="userId"
ref={useridInput}
onChange={(e)=> setInputValue(e.target.value)}
placeholder="userID 입력"
value={inputValue} />
<button onClick={onRest}>초기화</button>
<p>input: {inputValue}</p>
</div>
);
};
export default UseRefInput;
|
728x90
'React > React' 카테고리의 다른 글
React 카카오맵 API 사용 샘플 (0) | 2022.10.24 |
---|---|
React useMemo & useCallback (0) | 2022.10.24 |
React useReducer (0) | 2022.10.13 |
React-bootstrap Header.js 테스트 (0) | 2022.08.21 |
React CORS error 해결 방법 (0) | 2022.08.20 |