RN_Hooks

Mary·2025년 2월 6일

ReactNative

목록 보기
10/14
post-thumbnail

📢 React Native에서 Hooks란?

Hooks클래스형 컴포넌트 없이도 상태(state)와 생명주기(lifecycle) 기능을 사용할 수 있도록 하는 React 기능

React Native에서도 동일하게 사용되며, 함수형 컴포넌트에서 상태 관리와 효과(사이드 이펙트) 처리를 가능하게 해줌.


1️⃣ 왜 Hooks를 사용할까?

📍 기존 (클래스형 컴포넌트 문제점)

  • this.state, this.setState() 사용 → 불필요하게 복잡함
  • 생명주기 메서드 (componentDidMount, componentDidUpdate)가 분리되어 관리 어려움

Hooks의 장점

  • 클래스 없이 상태(state) 관리 가능
  • 생명주기 메서드보다 더 직관적으로 효과(Effect) 처리 가능
  • 로직을 재사용 가능 (Custom Hooks)

2️⃣ 주요 Hooks

React Native에서도 React와 동일하게 Hooks를 사용하며, 가장 많이 쓰는 Hooks는 다음과 같아.

Hook설명
useState상태(state) 관리
useEffect사이드 이펙트 (예: API 호출, 이벤트 리스너)
useRef컴포넌트의 DOM 요소나 값 유지 (초기화되지 않음)
useContext전역 상태 관리 (Redux 없이 간단한 상태 공유 가능)
useMemo값의 연산을 캐싱하여 성능 최적화
useCallback함수를 메모이제이션하여 불필요한 렌더링 방지

3️⃣ Hooks 사용 예제

(1) useState로 상태 관리

import React, { useState } from "react";
import { View, Text, Button } from "react-native";

const Counter = () => {
  const [count, setCount] = useState(0); // ✅ count 상태 선언

  return (
    <View>
      <Text>카운트: {count}</Text>
      <Button title="증가" onPress={() => setCount(count + 1)} />
    </View>
  );
};

export default Counter;

useState(0)count 상태를 0으로 초기화
setCount(count + 1) → 버튼 클릭 시 count 증가


(2) useEffect로 API 호출

import React, { useState, useEffect } from "react";
import { View, Text } from "react-native";

const UserInfo = () => {
  const [user, setUser] = useState(null);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/users/1")
      .then((res) => res.json())
      .then((data) => setUser(data)); // ✅ API 응답 데이터 저장
  }, []); // ✅ 빈 배열 → 마운트될 때 한 번만 실행

  return (
    <View>
      <Text>{user ? `이름: ${user.name}` : "로딩 중..."}</Text>
    </View>
  );
};

export default UserInfo;

useEffect(() => {...}, [])컴포넌트가 처음 렌더링될 때 한 번만 실행
setUser(data) → API 데이터를 받아 상태 업데이트


(3) useRef로 입력 필드 포커스 유지

import React, { useRef } from "react";
import { TextInput, Button, View } from "react-native";

const InputFocus = () => {
  const inputRef = useRef(null); // ✅ useRef로 참조값 저장

  return (
    <View>
      <TextInput ref={inputRef} style={{ borderBottomWidth: 1, padding: 10 }} />
      <Button title="포커스" onPress={() => inputRef.current.focus()} />
    </View>
  );
};

export default InputFocus;

useRef(null) → 입력 필드를 직접 참조
inputRef.current.focus() → 버튼 클릭 시 입력창에 포커스


(4) useMemo로 성능 최적화

import React, { useState, useMemo } from "react";
import { View, Text, Button } from "react-native";

const ExpensiveComponent = () => {
  const [count, setCount] = useState(0);
  const expensiveCalculation = useMemo(() => {
    console.log("계산 중...");
    return count * 2;
  }, [count]); // ✅ count가 변경될 때만 계산 실행

  return (
    <View>
      <Text>결과: {expensiveCalculation}</Text>
      <Button title="증가" onPress={() => setCount(count + 1)} />
    </View>
  );
};

export default ExpensiveComponent;

useMemo(() => ..., [count])count 변경 시에만 연산 수행
✔ 성능 최적화 → 불필요한 연산 방지


📢 최종 정리

Hook사용 목적예제
useState상태 관리 (State)const [count, setCount] = useState(0);
useEffectAPI 호출, 이벤트 리스너useEffect(() => fetchData(), []);
useRef요소 참조 (DOM, 값 유지)const inputRef = useRef(null);
useMemo연산 최적화const result = useMemo(() => expensiveFn(), [count]);
useCallback함수 메모이제이션const handleClick = useCallback(() => {...}, []);

0개의 댓글