feat: context factory
This commit is contained in:
31
src/lib/contextFactory/contextFactory.tsx
Normal file
31
src/lib/contextFactory/contextFactory.tsx
Normal file
@ -0,0 +1,31 @@
|
||||
"use client";
|
||||
|
||||
import React, { createContext, FC, PropsWithChildren, useContext } from "react";
|
||||
|
||||
export default function makeContext<State, HookArgs = {}>(
|
||||
useValue: (args: HookArgs) => State,
|
||||
displayName?: string
|
||||
) {
|
||||
const Context = createContext<State | undefined>(undefined);
|
||||
Context.displayName = displayName ?? "Custom";
|
||||
|
||||
const Provider: FC<PropsWithChildren<HookArgs>> = ({
|
||||
children,
|
||||
...hookArgs
|
||||
}) => {
|
||||
const value = useValue(hookArgs as HookArgs);
|
||||
return <Context.Provider value={value}>{children}</Context.Provider>;
|
||||
};
|
||||
|
||||
const useContextHook = () => {
|
||||
const context = useContext(Context);
|
||||
if (!context) {
|
||||
throw new Error(
|
||||
`${Context.displayName}Context must be used within ${Context.displayName}ContextProvider`
|
||||
);
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
return [Provider, useContextHook] as const;
|
||||
}
|
||||
Reference in New Issue
Block a user