1.useRef
useRef is React hook used by React to store values that are not required for rendering or to directly access DOM elements.
2. Sample Code
import logo from './logo.svg';
import './App.css';
import { useState, useEffect, useRef } from 'react';
import Timer from './component/Timer';
function App() {
const [count, setCount] = useState(0) //rendering occurs when state changes
const countRef = useRef(0) //rendring does not occur when ref changes
console.log('rendering...')
const increaseCountState = () => {
setCount(count + 1)
}
const increaseCountRef = () => {
countRef.current = countRef.current + 1
console.log('Ref : ', countRef.current)
}
return (
<div>
<p>State: {count}</p>
<p>Ref : {countRef.current}</p>
<button onClick={increaseCountState}>State 올려</button>
<button onClick={increaseCountRef}>Ref 올려</button>
</div>
);
}
export default App;
This code shows that useRef does not affect functional component's rendering.
3. Sample Code
import logo from './logo.svg';
import './App.css';
import { useState, useEffect, useRef } from 'react';
import Timer from './component/Timer';
function App() {
const inputRef = useRef();
useEffect(( )=> {
inputRef.current.focus()
})
const login = () => {
alert(`Welcome ${inputRef.current.value}`)
inputRef.current.focus()
}
return (
<div>
<input ref={inputRef} type="text" placeholder="username"/>
<button onClick={login}>Login</button>
</div>
);
}
export default App;
Using useRef, you can access DOM element.
When you open this page, useRef make input element focused.
Moreover, after user click login button, userRef make input element focused.
0 댓글