useState는 state가 변화될때 re render되지만, useRef는 값이 변경되더라도 re render되지 않는다.
import { useRef } from 'react';
import './App.css';
import AutoCounter from './components/AutoCounter';
import { Input } from './components/Input';
function App() {
const inputRef = useRef();
return (
<div>
<Input ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus</button>
<AutoCounter />
</div>
);
}
export default App;
import React, { useEffect } from 'react';
export const Input = React.forwardRef((_, ref) => {
useEffect(() => {
console.log(ref.current);
}, [ref]);
return (
<>
Input : <input ref={ref} />
</>
)
});
import React, { useRef, useState } from 'react';
export default function AutoCounter() {
const [count, setCount] = useState(0);
const intervalId = useRef();
const handleStart = () => {
intervalId.current = setInterval(() => {
setCount(count => count + 1)
}, 1000);
};
const handleStop = () => {
clearInterval(intervalId.current);
}
return (
<div>
<div>{count}</div>
<button onClick={() => handleStart}>Start</button>
<button onClick={() => handleStop}>Stop</button>
</div>
);
}