React Hooks 기초, 상태 관리부터 생명주기 이벤트

clock icon

posted 1 month ago

React Hooks는 함수형 컴포넌트에서 상태 관리, 생명주기 이벤트 처리 등 클래스 컴포넌트에서 가능했던 기능을 사용할 수 있게 해줍니다. 각 Hook은 특정한 용도로 사용되며, 이해하기 쉽게 각각의 용도와 사용 예를 설명하겠습니다.

 

1. useState

useState는 컴포넌트 내에서 상태(state)를 관리할 때 사용합니다. 이를 통해 변수의 값을 저장하고, 그 값을 업데이트할 수 있습니다.

 

import React, { useState } from 'react';

function Counter() {
  // count는 현재 상태, setCount는 상태를 업데이트하는 함수
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

 

2. useEffect

useEffect는 컴포넌트가 렌더링될 때마다 특정 작업을 수행할 수 있게 해주는 Hook입니다. 클래스 컴포넌트의 componentDidMount, componentDidUpdate, componentWillUnmount와 유사한 기능을 합니다.

 

import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  // count가 변경될 때마다 실행
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, [count]); // count가 변경될 때만 이 effect를 재실행

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

 

3. useRef

useRef는 DOM에 직접 접근할 때 사용합니다. 또한, 렌더링 간에 값을 유지할 수 있는 "상자"로도 사용됩니다.

 

import React, { useRef } from 'react';

function TextInputWithFocusButton() {
  const inputEl = useRef(null);

  const onButtonClick = () => {
    // 'current'는 타겟된 DOM을 가리킵니다.
    inputEl.current.focus();
  };

  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}

 

4. useMemo

useMemo는 복잡한 계산 결과값을 재사용함으로써 성능을 최적화할 때 사용합니다. 의존성 배열 내의 값이 변경될 때만 메모이제이션된 값을 재계산합니다.

 

import React, { useState, useMemo } from 'react';

function ComplexComponent() {
  const [count, setCount] = useState(0);
  const [word, setWord] = useState('');

  // 복잡한 계산 예
  const computeExpensiveValue = (a) => {
    console.log('Calculating...');
    return a * 2; // 실제로는 더 복잡한 계산이 이루어집니다.
  };

  const expensiveValue = useMemo(() => computeExpensiveValue(count), [count]);

  return (
    <div>
      <p>Value: {expensiveValue}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <input value={word} onChange={(e) => setWord(e.target.value)} />
    </div>
  );
}

 

각각의 Hook은 React에서 특정한 작업을 수행하기 위해 설계되었습니다. useState는 컴포넌트의 상태 관리를, useEffect는 부수 효과를 다루기 위해, useRef는 DOM 요소에 접근하거나 렌더링 간의 값을 유지하기 위해, 그리고 useMemo는 계산량이 많은 작업의 결과값을 메모이제이션하여 성능을 최적화하기 위해 사용됩니다.

Top Questions