topbg
React

Hooks

2023.01.31

React에서 다양한 hooks들

1. useState

prevState

const [state, setState] = useState({
  loading: false,
});

setState({ ...state, loading: true });
setState((prevState) => ({ ...prevState, loading: true }));

[Legacy][React] state, setState, useState 란 무엇일까?

2. useRef

변화는 감지 하지만, 그 변화가 랜더링이 발생시키면 안되는 어떤 값을 다룰때 사용한다. (리랜더링이 일어나지 않는다.)

import { useRef, useState } from "react";

const countRef = useRef(0);
const [renderer, setRenderer] = useState(0);

const increaseRef = () => {
  countRef.current = countRef.current + 1;
  console.log("Ref :", countRef.current);
};

const doRendering = () => {
  setRenderer(renderer + 1);
};

return (
  <div>
    <p>Ref: {countRef.current}</p>
    <button onClick={doRendering}>렌더!</button>
    <button onClick={increaseRef}>Ref UP</button>
  </div>
);

Result

DOM 요소에 접근

import { useEffect, useRef } from "react";

export default function App() {
  const inputRef = useRef();

  useEffect(() => {
    // console.log(inputRef);
    inputRef.current.focus();
  }, []);
  const login = () => {
    alert(`welcome ${inputRef.current.value}!`);
    inputRef.current.focus();
  };
  return (
    <div className="App">
      <input ref={inputRef} type="text" placeholder="username" />
      <button onClick={login}>로그인</button>
    </div>
  );
}

Dom 요소 접근

reference

이해한 것을 정리하다보니
잘못된 부분이 있을 수도 있습니다.
댓글로 잘못된 부분을 알려주세요.