[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;
};
반응형
'한 걸음 > React & Next.js' 카테고리의 다른 글
[Next.js] 비회원이 로그인 후 원래 있던 페이지로 돌아올 수 있도록 하기 (0) | 2025.02.24 |
---|---|
[Next.js + Typescript] 컴포넌트 자체를 넘겨받아 렌더링하기 (0) | 2024.12.17 |
build 결과물에서 정보를 숨기고 싶을 때 (0) | 2024.07.17 |
[npm] 라이브러리 배포 시, subpath로 깔끔하게 내보내기 (0) | 2024.06.21 |
[React] svg icon 컴포넌트화해서 사용하기 (0) | 2024.06.04 |