useRef란?

useRef와 useState의 차이

useRef useState
Reference 객체를 생성 State를 생성
컴포넌트 내부의 변수로 활용 가능 컴포넌트 내부의 변수로 활용 가능
어떤 경우에도 리렌더링을 유발하지 않는다. 값이 변경되면 컴포넌트 리렌더링

useRef 동작 원리

변경된 수정 횟수 카운트 하는 기능 만들기

import { useState, useRef } from "react";

// 간단한 회원가입 폼
// 이름, 생년월일, 국적, 자기소개

const Register = () => {
  const [input, setInput] = useState({
    name: "",
    birth: "",
    country: "",
    bio: "",
  });

  const countRef = useRef(0);

  const onChange = (e) => {
    countRef.current++; // 수정한 횟수
    console.log(countRef.current);
    setInput({
      ...input,
      [e.target.name]: e.target.value,
    });
  };

화면 결과

image.png

회원가입 제출 기능 만들기