본문 바로가기
더이상 하지 않는 망한 프로젝트/chatGPT

[리액트네이티브] 자주 사용되는 Hooks 정리

by VictorMeredith 2023. 3. 21.

리액트네이티브(React Native)는 React의 모바일 프레임워크로, 하나의 코드베이스로 iOS와 Android 애플리케이션을 만들 수 있습니다. 

이 글에서는 리액트네이티브에서 자주 사용되는 훅(hook)들과 언제 사용하는지에 대해 알아보겠습니다.

리액트 네이티브

useState

useState는 컴포넌트에서 상태를 관리할 수 있는 기본적인 훅입니다. 상태가 변경될 때마다 컴포넌트가 리렌더링되므로 동적인 데이터를 관리할 때 유용합니다.

import React, { useState } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';

const Counter = () => {
  const [count, setCount] = useState(0);

  return (
    <View>
      <Text>{count}</Text>
      <TouchableOpacity onPress={() => setCount(count + 1)}>
        <Text>증가</Text>
      </TouchableOpacity>
    </View>
  );
};

 

useEffect

useEffect는 컴포넌트 라이프 사이클에 따른 부수적인 효과를 처리할 때 사용되는 훅입니다. 컴포넌트가 마운트, 업데이트 또는 언마운트될 때 실행할 작업을 지정할 수 있습니다.

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

const Timer = () => {
  const [time, setTime] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setTime(time + 1);
    }, 1000);

    return () => {
      clearInterval(interval);
    };
  }, [time]);

  return (
    <View>
      <Text>{time}초 경과</Text>
    </View>
  );
};

 

useContext

useContext 훅을 사용하면 컴포넌트 트리를 통해 전달되는 프롭스를 쉽게 소비할 수 있습니다. 컨텍스트를 사용하면 글로벌 상태를 관리하고, 깊게 중첩된 컴포넌트에도 데이터를 전달할 수 있습니다.

import React, { createContext, useContext, useState } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';

const CountContext = createContext();

const CounterDisplay = () => {
  const { count } = useContext(CountContext);
  return <Text>{count}</Text>;
};

const Counter = () => {
  const [count, setCount] = useState(0);
  const value = { count, setCount };

  return (
    <CountContext.Provider value={value}>
      <CounterDisplay />
      <TouchableOpacity onPress={() => setCount(count + 1)}>
        <Text>증가</Text>
      </TouchableOpacity>
    </CountContext.Provider>
  );
};

 

useMemo

useMemo는 값이 변경되었을 때만 다시 계산되는 메모이제이션된 값을 반환하는 훅입니다. 이를 사용하면 불필요한 연산을 줄이고 성능을 최적화할 수 있습니다.

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

const calculateFactorial = (num) => {
  if (num <= 1) return 1;
  return num * calculateFactorial(num - 1);
};

const Factorial = () => {
  const [input, setInput] = useState(5);
  const factorial = useMemo(() => calculateFactorial(input), [input]);

  return (
    <View>
      <Text>입력 값: {input}</Text>
      <Text>팩토리얼: {factorial}</Text>
    </View>
  );
};

 

useCallback

useCallback은 콜백 함수를 메모이제이션하는데 사용되는 훅입니다. 의존성 배열에 명시된 값이 변경되지 않는 한, 동일한 함수 참조를 반환합니다. 이는 자식 컴포넌트에 함수를 전달하거나, 불필요한 리렌더링을 방지할 때 유용합니다.

import React, { useState, useCallback } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';

const Counter = ({ onIncrement }) => {
  const [count, setCount] = useState(0);

  const increment = useCallback(() => {
    setCount(count + 1);
    onIncrement();
  }, [count, onIncrement]);

  return (
    <View>
      <Text>{count}</Text>
      <TouchableOpacity onPress={increment}>
        <Text>증가</Text>
      </TouchableOpacity>
    </View>
  );
};

 

useRef

useRef는 변경 가능한 객체를 반환하는 훅으로, 주로 DOM 노드를 참조하거나 값이 변경되어도 리렌더링을 일으키지 않는 인스턴스 변수를 관리하는데 사용됩니다.

import React, { useRef, useState } from 'react';
import { View, Text, TextInput, TouchableOpacity } from 'react-native';

const TextInputWithFocusButton = () => {
  const [text, setText] = useState('');
  const inputRef = useRef(null);

  const handleFocus = () => {
    inputRef.current.focus();
  };

  return (
    <View>
      <TextInput
        ref={inputRef}
        value={text}
        onChangeText={setText}
        placeholder="여기에 텍스트를 입력하세요."
      />
      <TouchableOpacity onPress={handleFocus}>
        <Text>포커스</Text>
      </TouchableOpacity>
    </View>
  );
};

 

useReducer


useReducer는 복잡한 상태 로직을 관리하는 데 사용되는 훅입니다. 상태 업데이트 로직을 리듀서 함수에 작성하여 복잡한 상태를 처리하고, 컴포넌트 코드를 깔끔하게 유지할 수 있습니다.

import React, { useReducer } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';

const initialState = { count: 0 };

const reducer = (state, action) => {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    default:
      throw new Error();
  }
};

const Counter = () => {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <View>
      <Text>{state.count}</Text>
      <TouchableOpacity onPress={() => dispatch({ type: 'increment' })}>
        <Text>증가</Text>
      </TouchableOpacity>
    </View>
  );
};

 

useLayoutEffect

useLayoutEffect는 컴포넌트 렌더링 이후에 동기적으로 실행되는 훅입니다. 일반적으로 useEffect와 동일한 목적으로 사용되지만, DOM 업데이트가 화면에 반영되기 전에 완료되어야 하는 경우 사용합니다.

import React, { useState, useLayoutEffect } from 'react';
import { View, Text } from 'react-native';

const MeasureBox = () => {
  const [width, setWidth] = useState(0);

  useLayoutEffect(() => {
    setTimeout(() => {
      setWidth(200);
    }, 1000);
  }, []);

  return (
    <View>
      <Text>박스 너비: {width}px</Text>
    </View>
  );
};

 

 

이렇게 리액트네이티브에서 사용할 수 있는 다양한 훅들이 있습니다. 이러한 훅들은 상황에 따라 적절히 사용되어야 합니다. 따라서 개발자는 프로젝트의 요구 사항과 목적에 맞게 각 훅을 선택하여 사용하는 것이 중요합니다. 또한, 커스텀 훅을 만들어서 애플리케이션의 로직을 더욱 캡슐화하고 재사용성을 높일 수도 있습니다.

댓글