useContext를 이용한 Custom Hook 생성
  1. Custom Hook이란?
  2. useContext를 이용한 Custom Hook 생성
  3. Custom Hook 사용 예시
  4. 참고 자료

1. Custom Hook이란?

Custom Hook은 React에서 상태 관리와 같은 로직을 재사용하기 위해 사용되는 함수입니다. Custom Hook은 기존의 React Hook들을 사용하여 작성되며, 컴포넌트의 로직을 분리하여 재사용성을 높이는데 도움이 됩니다.

2. useContext를 이용한 Custom Hook 생성

React에서 제공하는 Context API를 활용하여 useContext를 이용하여 Custom Hook을 생성할 수 있습니다. useContext를 사용하면 컴포넌트 간에 상태를 공유할 수 있습니다.

다음은 useContext를 이용하여 Custom Hook을 생성하는 예제 코드입니다.

import React, { createContext, useContext } from 'react';

// 새로운 Context 생성
const MyContext = createContext();

// Provider 컴포넌트 생성
const MyProvider = ({ children }) => {
  // 상태 값 설정
  const state = {
    name: 'John',
    age: 25,
  };

  return (
    <MyContext.Provider value={state}>
      {children}
    </MyContext.Provider>
  );
};

// Custom Hook 생성
const useCustomHook = () => {
  // Context 사용
  const context = useContext(MyContext);

  return context;
};

export { MyProvider, useCustomHook };

위의 코드에서는 MyContext라는 새로운 Context를 생성하고, MyProvider라는 Provider 컴포넌트를 만듭니다. MyProvider 컴포넌트는 value prop으로 상태 값을 전달하고, useCustomHook이라는 Custom Hook을 생성합니다. 이 Custom Hook을 다른 컴포넌트에서 사용하여 해당 Context의 상태 값을 가져올 수 있습니다.

3. Custom Hook 사용 예시

이제 위에서 생성한 Custom Hook을 사용하는 예시를 보겠습니다.

import React from 'react';
import { MyProvider, useCustomHook } from './CustomHook';

const App = () => {
  // Custom Hook 사용
  const { name, age } = useCustomHook();

  return (
    <>
      <h1>{name}</h1>
      <p>{age} years old</p>
    </>
  );
};

const Root = () => {
  return (
    // Provider로 감싸기
    <MyProvider>
      <App />
    </MyProvider>
  );
};

export default Root;

위의 코드에서는 Custom Hook을 불러와서 nameage 상태 값을 가져온 다음, 컴포넌트 내에 출력하는 예시입니다. MyProvider 컴포넌트로 App 컴포넌트를 감싸서 상태 값을 제공해주어야 합니다.

4. 참고 자료