본문 바로가기
코딩이야기/React 공부

[React] React-Hooks 간단 정리 (1)

by TaeHyeon0412 2024. 7. 3.

대표적인 React-Hooks

• useState

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 기존에 우리가 사용하던 일반 방식
setState(number + 1);
 
// 함수형 업데이트 
setState((currentNumber)=>return currentNumber + 1 });
 
**차이점
 
 <button
        onClick={() => {
          setNumber(number + 1); // 첫번째 줄 
          setNumber(number + 1); // 두번쨰 줄
          setNumber(number + 1); // 세번째 줄
        }}
      />
// 코드가 3개를 써놔도 1번만 실행되어서 1만 증가
 
<button
        onClick={() => {
          setNumber((previousState) => previousState + 1);
          setNumber((previousState) => previousState + 1);
          setNumber((previousState) => previousState + 1);
        }}
      />
// 코드 3개를 하나로 모아 실행하여 3이 증가
cs

왜 리액트팀은 useState가 위 방식으로 동작하도록 만들었을까?

공식문서 : 리액트는 성능을 위해 setState()를 단일 업데이트(batch update)로 한꺼번에 처리할 수 있습니다.
공식문서의 설명처럼, 불필요한 리-렌더링을 방지(렌더링 최적화)하기 위해 즉, 리액트의 성능을 위해 한꺼번에 state를 업데이트 한다고 합니다.

 


•useEffect

리액트 컴포넌트가 렌더링될 때마다 특정 작업을 수행하도록 설정할 수 있는 Hook 쉽게 말해 어떤 컴포넌트가
화면에 보여졌을 때 내가 무언가를 실행하고 싶다면?
또는 어떤 컴포넌트가 화면에서 사라졌을 때 무언가를 실행하고 싶다면 사용합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// src/App.js
 
import React, { useEffect } from "react";
 
const App = () => {
 
    useEffect(()=>{
        // 화면에 컴포넌트가 나타났을(mount) 때 실행하고자 하는 함수를 넣어주세요.
 
        return ()=>{
            // 화면에서 컴포넌트가 사라졌을(unmount) 때 실행하고자 하는 함수를 넣어주세요.
        }
    }, [])
 
    return <div>hello react!</div>
};
 
export default App;
cs

 

 


•useRef

DOM 요소에 접근할 수 있도록 하는 React Hook DOM을 선택해야 할 상황 예시
=>화면이 렌더링 되자마자 특정 input 태그가 focusing이 돼야 하는 경우에 사용합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import "./App.css";
import { useRef } from "react";
 
function App() {
  const ref = useRef("초기값");
  console.log("ref", ref);
 
  return (
    <div>
      <p>useRef입니다.</p>
    </div>
  );
}
 
export default App;
 
//console.log => ref = current : "초기값"
 
////////////////////////////////////
 
import "./App.css";
import { useRef } from "react";
 
function App() {
  const ref = useRef("초기값");
  console.log("ref 1", ref);
 
  ref.current = "바꾼 값";
  console.log("ref 1", ref);
 
  return (
    <div>
      <p>useRef입니다.</p>
    </div>
  );
}
 
export default App;
 
//console.log => ref = current : "초기값"
//console.log => ref = current : "바꾼 값"
 
/*
(중요) 이렇게 설정된 ref 값은 컴포넌트가 계속해서 렌더링 되어도 unmount 전까지 값을 유지합니다!
*/
cs

내부 변수 let을 쓰면 렌더링 시 변수가 초기화 되는데 useRef를 쓰면 렌더링이 되어도 값이 유지 됩니다.

 


•useContext

props를 사용하여 데이터를 전달해 줄 때 생기는 문제점 중 prop drilling 현상을 해결하기 위해 나온 전역 데이터 관리 방법입니다.

context API 필수 개념
- createContext : context 생성
- Consumer : context 변화 감지
- Provider : context 전달(to 하위 컴포넌트)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
//Context.js
import { createContext } from "react";
 
export const FamilyContext = createContext(null);
 
 
//GrandFather.jsx
import React from "react";
import Father from "./Father";
import { FamilyContext } from "../context/FamilyContext";
 
function GrandFather() {
  const houseName = "동동";
  const money = 50000;
 
  return (
    <FamilyContext.Provider value={{ houseName, money }}>
      <Father />
    </FamilyContext.Provider>
  );
}
 
export default GrandFather;


/*<FamilyContext.Provider value={{ houseName, money }}>로
데이터를 context에 저장*/



//child.jsx
import React, { useContext } from "react";
import { FamilyContext } from "../context/FamilyContext";
 
function Child({ houseName, money }) {
  const stressedWord = {
    color: "red",
    fontWeight: "900",
  };
 
  const data = useContext(FamilyContext);
  console.log("data", data);
 
  return (
    <div>
      할아버지가 우리 집 이름은 <span>{data.houseName}</span>
      라고 하셨어요.
      <br />
      용돈도 <span style={stressedWord}>{data.money }</span>원 주셨어요.
    </div>
  );
}
 
export default Child;
 
/*GrandFather → Context(중앙 관리소) → Child 순서로 전달
const data = useContext(FamilyContext);를 이용하여 context에 저장된 정보를 바로 불러오기*/
cs