본문 바로가기

👻내일배움캠프 - 스파르타코딩클럽/TlL

240520 TIL

 

오늘의 공부 : 리액트 숙련 강의 들으며 차근차근 정리 중이다! 과제 전에 까먹으면 안 될 듯.. ㅠㅠ 

 

useEffect 

import { useEffect, useRef, useState } from "react";
import "./App.css";

function App() {
  const [value, setValue] = useState("");
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log("hello useEffect");
  }, []);

  return (
    <div>
      <h1>useEffect</h1>
      <input
        type="text"
        value={value}
        onChange={(e) => {
          setValue(e.target.value);
        }}
      />
      {count}
      <button
        onClick={() => {
          setCount(count + 1);
        }}
      >
        증가
      </button>
    </div>
  );
}

 

 

 

useRef

import { useEffect, useRef, useState } from "react";
import "./App.css";

const [count, setCount] = useState(0);
  const countRef = useRef(0);

  const plusStateCountButtonHandler = () => {
    setCount(count + 1);
  };

  const plusRefCountButtonHandler = () => {
    countRef.current++;
  };
  return (
    <div>
      <h1>useRef vs useState</h1>
      <div>
        state영역입니다. {count} <br />
        <button onClick={plusStateCountButtonHandler}>state 증가</button>
      </div>
      <div>
        ref영역입니다. {countRef.current} <br />
        <button onClick={plusRefCountButtonHandler}>ref 증가</button>
      </div>
    </div>
  );

 

 

useState / useRef의 차이 

import { useEffect, useRef, useState } from "react";
import "./App.css";

const [count, setCount] = useState(0);
  const countRef = useRef(0);

  const plusStateCountButtonHandler = () => {
    setCount(count + 1);
  };

  const plusRefCountButtonHandler = () => {
    countRef.current++;
  };
  return (
    <div>
      <h1>useRef vs useState</h1>
      <div>
        state영역입니다. {count} <br />
        <button onClick={plusStateCountButtonHandler}>state 증가</button>
      </div>
      <div>
        ref영역입니다. {countRef.current} <br />
        <button onClick={plusRefCountButtonHandler}>ref 증가</button>
      </div>
    </div>
  );

 

 

 

state는 눌렀을 때 count가 올라간다. 하지만 ref는 아무리 눌러도  값이 보이지 않는데, 

ref는 state를 한번 눌러줄 때만  값이 나타난다. ★

 

 

 

 

import { useEffect, useRef, useState } from "react";
import "./App.css";

function App() {
  const idRef = useRef("");
  useEffect(() => {
    idRef.current.focus;
  }, []);

  return (
    <div>
      <div>
        아이디 : <input type="text" />
      </div>
      <div>
        비밀번호 : <input type="password" ref={idRef} />
      </div>
    </div>
  );
}

export default App;

 

 

id 입력하는 부분에 포커스를 맞추어 사용자가 바로 id를 입력할 수 있게 하는 방법이다.

 

내일도 공부 파이팅.. 과제도 파이팅!

'👻내일배움캠프 - 스파르타코딩클럽 > TlL' 카테고리의 다른 글

240522 TIL  (0) 2024.05.22
240521 TIL  (0) 2024.05.21
240517 TIL  (0) 2024.05.17
240516 TIL  (0) 2024.05.16
240515 TIL  (0) 2024.05.15