[React] context API 기본구조

2024. 11. 25. 14:10
반응형

쓸 때마다 까먹네...

 

'use client';

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

const SellContext = createContext<
  | {
      name: string;
      setName: (value: string) => void;
    }
  | undefined
>(undefined);

export const SellContextProvider: React.FC<{ children: React.ReactNode }> = ({
  children,
}) => {
  const [name, setName] = useState('');

  return (
    <SellContext.Provider
      value={{
        name,
        setName,
      }}
    >
      {children}
    </SellContext.Provider>
  );
};

export const useSellContext = () => {
  const context = useContext(SellContext);
  if (!context) {
    throw new Error('useAppContext must be used within an AppProvider');
  }
  return context;
};
반응형

BELATED ARTICLES

more