[React] useRef

Jin·2023년 3월 10일
0

react

목록 보기
10/11
post-thumbnail

useRef를 쓰는 이유

  1. DOM에 직접 접근하기 위해
  2. 지역변수로 사용하기 위해

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>
  );
}

0개의 댓글